how to add an :eq filter counter to an empty unordered list?
I finally figure out how to ask the right question, and that is, how to add an :eq filter counter to an empty unordered list?
For example, the code below does not seem to add li data only whe开发者_如何学Gon the ul/li is empty.
<button id="go">Add</button><br>
<label>Position to Add: <input id="pos" value="2" type="text" maxlength="1"</label>
<br>
<label>Text to Add: <input id="newText" value="New Item" type="text"></label><br>
<br>
<ul id="list"> </ul>
$("#go").click(function() {
var item = $("#newText").val();
var n = parseInt($("#pos").val(), 10);
$('#list li').eq(n).after('<li>' + item + '</li>')
});
If I manually add an item to the list, then the jquery code below works.
<button id="go">Add</button><br>
<label>Position to Add: <input id="pos" value="2" type="text" maxlength="1"</label>
<br>
<label>Text to Add: <input id="newText" value="New Item" type="text"></label><br>
<br>
<ul id="list"><li> test </li> </ul>
$("#go").click(function() {
var item = $("#newText").val();
var n = parseInt($("#pos").val(), 10);
$('#list li').eq(n).after('<li>' + item + '</li>')
});
Here is a working example: http://jsfiddle.net/geb6p/
In the code, I check if there are any child elements in "ul", if not then append a child of 'li'
It's invalid HTML (at least for 4.01) to have an empty UL or OL. Firefox will actually add an empty LI to the DOM on your behalf, which could cause issues in the future. More importantly, though, you are trying to create a jQuery object with $('#list li')
, a node which doesn't exist yet at all (regardless of eq(n)
).
精彩评论