使用 jQuery 的元素长度为 0

Length of elements using jQuery is 0

我正在尝试使用以下代码填充 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。

上面的代码有问题吗?

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

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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="the-list"></ul>