pix*_*e54 9 jquery attributes element
我基本上都试图完成主题所暗示的内容,但我在警报中得到"未定义",我不完全确定原因.我对jquery相当新,所以,我可能有错误的语法,但不知道从哪里开始.我将发布我的两次尝试,这两次尝试都会在警报中产生"未定义"...
//In my first attempt, I'm trying to get the id of the inner a tag
<ul>
<li id="l1" class="active"><a href="#c1">Samp 1</a></li>
<li id="l2" class=""><a href="#c2">Samp 2</a></li>
<li id="l3" class=""><a href="#c3">Samp 3</a></li>
</ul>
var selected = $(".active).children("a").attr("id");
alert(selected);
//In my second attempt, I'm trying to get the id of the currently selected li
var selected = $(".active").attr("id");
alert(selected);
Run Code Online (Sandbox Code Playgroud)
Vin*_*ert 20
$(".active").children("a").attr("id");
Run Code Online (Sandbox Code Playgroud)
你的<a>元素没有id,只有一个href.使用选择器而不是子函数可以使您的代码更容易阅读.
你的意思是$(".active > a").attr("href")?
$(".active").attr("id");
Run Code Online (Sandbox Code Playgroud)
jQuery将返回idjQuery集合中第一个元素的属性.你有另一个课程元素active吗?
我建议你试试 $("ul > li.active").attr("id")