I am trying to populate a ul with the following code
我正在尝试使用以下代码填充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);
The first alert gives me the proper value. But the second alert shows a length of 0.
第一个警报给了我正确的价值。但第二个警报显示长度为0。
Is there something wrong with the above code?
上面的代码有问题吗?
1 个解决方案
#1
Your call at the end is searching the DOM, but you've never added those elements to the DOM. If you added them, they'd show up on the search:
您最后的调用是搜索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>
#1
Your call at the end is searching the DOM, but you've never added those elements to the DOM. If you added them, they'd show up on the search:
您最后的调用是搜索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>