我正在尝试将列表元素动态附加到现有列表中。
我在表单中有一个列表,
<ul id="test">
<li class="testField">YYAAHOOOOOO<li>
</ul>
我正在尝试使用jQuery append或之后添加一个额外的项目到此列表
我做的是:
$(".testField").after("<li class='testField'>TEST MESSENGER</li>");
在函数as append不起作用后使用,after函数第一次工作正常,因为只有一个元素具有类名testField
,但随着列表的增长,after函数将列表项添加到所有元素都存在,
为清楚起见,在第一次试用时我会得到一个输出:
<ul id="test">
<li class="testField">YYAAHOOOOOO<li>
<li class='testField'>TEST MESSENGER</li>
</ul>
如果我现在尝试添加另一个元素,例如<li class='testField'>GOOGLE</li>
,输出将如下:
<ul id="test">
<li class="testField">YYAAHOOOOOO<li>
<li class='testField'>GOOGLE</li>
<li class='testField'>TEST MESSENGER</li>
<li class='testField'>GOOGLE</li>
</ul>
我考虑过使用id,但我试图有一个选项来从列表中删除元素......所以如果我尝试追加到未定义的id,它将返回错误。有没有找到列表中的第一个元素并将元素追加到第一个元素?
答案 0 :(得分:5)
尝试:
$(".testField:first").after("<li class='testField'>TEST MESSENGER</li>");
这将确保您仅在第一个元素之后追加
答案 1 :(得分:0)
或者,您可以在没有jQuery的情况下执行此操作:
var li = document.createElement('li'); // Create a List item.
li.setAttribute("class", "testfield"); // Set the li's class
li.addChild(document.createTextNode("Your Text Here!")); // Set the li's text
document.getElementById("test").addChild(li); // Append the li to the list
这是稍微多一点的代码,是的,但它几乎就是jQuery所做的。 (而且速度也快)
如果您想在列表中的第一个li
之后添加新的ul,请将最后一行替换为:
var ul = document.getElementById("test");
if(ul.children.length > 1){ // If the list has 2 or more children (li's)
ul.insertBefore(li, ul.children[1]); // Insert the new item before the second item in the list.
}else{
document.getElementById("test").addChild(li);
}
现在,为什么我发布需要更多代码的答案? 可以在jQuery中完成的任何事情都可以在本机JS中完成。我认为在SO上提供多个不同的答案是很好的,特别是如果他们使用不同的技术来做同样的事情。这样,用户可以自己选择:short'n easy(jQuery),或者如果他们不想使用库,本机代码。