2013-08-20 28 views
1

我有以下代碼:lastChild不工作

<!DOCTYPE html> 
<html> 
<head> 
<meta charset = "utf-8"/> 
<script type = "text/javascript" src = "js/jquery.js" ></script> 
</head> 
<body> 
<div id = 'div'> 
    <div id = "1"> 

    </div>  
    <div id = "2"> 

    </div> 
</div>   
</body> 
</html> 

我的JavaScript代碼是:

$(document).ready(function(){ 
    var lastcommentq = document.getElementById('div').lastChild.id; 
    alert(lastcommentq); 
}); 

應該警惕與ID爲 '格',這是div的lastchild的id '2',但我得到的警報爲「未定義」。我不知道我做錯了什麼。請幫幫我。

+0

您正在提醒'lastcommentq',那是什麼?你的變量被稱爲'lastchild'。 –

+3

如果您使用jQuery,爲什麼使用getElementById而不是jQuery的本機選擇器? –

+0

@RocketHazmat這是一個錯誤。我糾正了它.. – user1763032

回答

7

您的元素周圍可能有文本節點,因此外部<div>的最後一個子節點不一定具有「id」屬性。

我不確定是否所有的瀏覽器都支持它,但是有一個「lastElementChild」屬性只顯示元素,而不是註釋節點或文本節點。否則,您可以循環查找類型1節點的節點列表。

+1

['lastElementChild'](https://developer.mozilla.org/en-US/docs/Web/API/ParentNode.lastElementChild)似乎在大多數瀏覽器上工作。 –

+0

That worked .. thanks .. – user1763032

0

這是你想要的行爲?

$(document).ready(function(){ 
    var lastchild = $("div").last().attr("id") 
    alert(lastchild); 
    }); 


<div id="div"> 
    <div id ="1"> 

    </div>  
    <div id="2"> 

    </div> 
</div>   

退房這個搗鼓活生生的例子

http://jsfiddle.net/sHgbF/

+0

他似乎在尋找'$('#div')。children('div')。last()。attr('id')'。 –

0

這就是我會做,但我並不清楚,如果這是你想要的東西:

$(function() { 
    var lastchild = $('#div div:last-child').attr('id'); 
    alert(lastchild); 
}); 

http://jsfiddle.net/pFjPS/

另外,我不相信類或ID可以以數字開頭,因此您的標記可能無效

編輯: HTML5支持它,但通常不推薦使用。

+1

ID不能以HTML 4.01及以前版本的數字開頭。我相信課程可以從數字開始。 –

+0

它看起來不像類可以:http://stackoverflow.com/questions/4089006/can-xhtml-and-html-class-attributes-value-start-with-a-number –

+1

從技術上講,他們[可以在HTML](http://www.w3.org/html/wg/drafts/html/master/dom.html#classes),但[不在CSS](http://www.w3.org/TR/css3 -syntax /#個字符) –

0

jQuery中:

$(function(){ 
    alert($("#div :last-child").attr('id')); 
}); 
0

我會用這種方法,因爲ID是一個屬性,而不是一個屬性。

$(function() { 
    var lastchild = $('#div div:last-child').prop('id'); 
    alert(lastchild); 
}); 
+1

[「要在使用時達到最佳性能:最後選擇元素,請首先使用純CSS選擇器選擇元素」](http://api.jquery.com/last-selector/)。由於我們已經有了一個純粹的CSS選擇器,':last-child',不需要':last'。 –

+0

哇@ rink.attendant.6多數民衆贊成的信息,使用最後孩子,而不是從現在開始 –

0

jQuery的方式:

// assuming the last child is always a div 
var lastcommentq = $('#div > div:last-child').attr('id'); 

// alternatively 
var lastcommentq0 = $('#div').children('div').last().attr('id'); 

JavaScript的方式:

var lastcommentq = document.getElementById('div').lastElementChild.id; 

請注意,這適用於所有現代瀏覽器和IE 9+。請參閱MDN上的lastElementChild