使用jQuery的元素长度为0

时间:2015-05-11 08:46:50

标签: jquery list attributes

我正在尝试使用以下代码填充ul

item = []
item.push('<li title ="head"' + 'id="' + innerValue + '">' + innerKey + " : " + innerValue + '</li>');

alert('<li title ="head"' + 'id="' + innerValue + '">' + innerKey +" : " + innerValue + '</li>');
alert($('[title="head"]').length);

第一个警报给了我正确的价值。 但第二个警报显示长度为0.

上述代码有问题吗?

1 个答案:

答案 0 :(得分:5)

您最后的电话是搜索DOM,但您从未将这些元素添加到DOM中。如果您添加了它们,它们就会出现在搜索中:

&#13;
&#13;
var item = [];
var innerValue = "value";
var innerKey = "key";
item.push('<li title ="head"' + 'id="' + innerValue + '">' + innerKey + " : " + innerValue + '</li>');
alert("Before adding to the DOM: " + $('[title="head"]').length);
$("#the-list").append(item[0]);
alert("After adding to the DOM: " + $('[title="head"]').length);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="the-list"></ul>
&#13;
&#13;
&#13;