获取子元素的id并使用jquery存储在变量中?

前端之家收集整理的这篇文章主要介绍了获取子元素的id并使用jquery存储在变量中?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我基本上都试图完成主题所暗示的内容,但我在警报中得到“未定义”,我不完全确定原因.我对 jquery相当新,所以,我可能有错误的语法,但不知道从哪里开始.我将发布我的两次尝试,这两次尝试都会在警报中产生“未定义”…
  1. //In my first attempt,I'm trying to get the id of the inner a tag
  2. <ul>
  3. <li id="l1" class="active"><a href="#c1">Samp 1</a></li>
  4. <li id="l2" class=""><a href="#c2">Samp 2</a></li>
  5. <li id="l3" class=""><a href="#c3">Samp 3</a></li>
  6. </ul>
  7.  
  8. var selected = $(".active).children("a").attr("id");
  9. alert(selected);
  10.  
  11. //In my second attempt,I'm trying to get the id of the currently selected li
  12. var selected = $(".active").attr("id");
  13. alert(selected);

解决方法

@H_502_7@
  1. $(".active").children("a").attr("id");

你的< a>元素没有id,只有一个href.使用选择器而不是子函数可以使您的代码更容易阅读.

你的意思是$(“.active> a”).attr(“href”)?

  1. $(".active").attr("id");

jQuery将返回jQuery集合中第一个元素的id属性.你有另一个活跃的类元素吗?

我建议你试试$(“ul> li.active”).attr(“id”)

猜你在找的jQuery相关文章