2015-05-11 86 views
-1

我试图填充UL用下面的代码长度为0

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.

上述代码有问题吗?

回答

5

您最后的调用是搜索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

谢谢T.J.你是对的。我不知何故错过了这一步。 – Neel