lastChild not working
lastChild not working
我有以下代码:
<!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"警告div的最后一个子项的id,它是"2",但我得到的警告是"未定义的"。我不知道我做错了什么。请帮帮我。
您的元素周围可能有文本节点,因此外部<div>
的最后一个子节点不一定具有"id"属性。
我不确定是否所有浏览器都支持它,但有一个"lastElementChild"属性显式地只获取元素,而不获取注释节点或文本节点等内容。如果做不到这一点,您可以在节点列表中循环查找类型1的节点。
这是你想要的行为吗?
$(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/
在jquery中:
$(function(){
alert($("#div :last-child").attr('id'));
});
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。
这是我本想做的,但我不清楚这是否是你想要的:
$(function () {
var lastchild = $('#div div:last-child').attr('id');
alert(lastchild);
});
http://jsfiddle.net/pFjPS/
另外,我不相信类或id可以以数字开头,所以您的标记可能不是有效的
编辑:HTML5支持它,但通常不推荐使用。
我会使用这种方法,因为ID是一个属性,而不是属性。
$(function () {
var lastchild = $('#div div:last-child').prop('id');
alert(lastchild);
});
相关文章:
- $rootScope not working
- jQuery document.ready not working
- Javascript getElementsByTagName not working?
- JQuery.val( ) not working
- Tomcat websocket is not working
- Javascript JSON.parse not working
- NodeJS Multer is not working
- Regex not working
- Ember run.debounce not working
- AngularJs 1 not working
- document.getElementById.style.backgroundImage not working
- Rxjs5, distinct() is not working
- createOscillator noteOn not working
- Javascript - .getHours() not working
- Javascript setTimeout not working | onkeydown
- MongoDB $pull not working
- Express router.use not working
- JSONP not working
- window.opener not working in chrome & IE
- Backbone + RequireJS: Collection.each() is not working