2010-05-25 69 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

相關問題