2010-05-25 66 views
7

我基本上试图完成主题所暗示的内容,但我的警报中出现“未定义”,我不完全确定原因。我对jQuery相当陌生,所以,我可能有语法错误,但不知道从哪里去。我会后我的两个尝试,其产量都在警报“未定义” ......获取一个id元素的子元素并存储在一个变量使用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); 

回答

12
$(".active").children("a").attr("id"); 

<a>元素没有一个id,只有href。使用选择器而不是子功能可能会使您的代码更易于阅读。

你的意思是$(".active > a").attr("href")


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

jQuery将返回的第一个元素的id属性jQuery的收藏。你有另一个类active

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

0

问题与锚似乎是没有你实际上选择锚有一个ID。你的意思是.attr("href")有没有机会?

1

在第一次尝试,你得到<a><li>内......不有一个ID,你只需要这样:

var selected = $(".active").attr("id"); 
alert(selected); 

所以你的第二次尝试是正确的,you can see it in action here

如果您确实打算从<a>元素获取id,那么您需要为它们提供ID,并且您的第一次尝试将起作用you can see it here

-1

您收到错误的属性(或者您有错误的标记)。你的标签中没有“id”属性。如果你需要得到父母的ID,你应该使用,否则

var selected = $(".active).children("a").attr("href"); 
    alert(selected); 

var selected = $(".active).attr("id"); 
    alert(selected); 
你的“href”属性,因此,如果你想GETH的的“href”的值,你应该使用这个
+0

你缺少双引号。 – 2017-01-04 13:02:58

相关问题