使用jQuery时出现奇怪的插入问题

4
我得到了一个列表,想要通过Javascript中断来添加标题:
从:
<ul>
    <li>1</li>
    <li class="afterthis">2</li>
    <li>3</li>
    <li>4</li>
</ul>

收件人:
<ul>
    <li>1</li>
    <li class="afterthis">2</li>
</ul>
<h1>Title</h1>
<ul>
    <li>3</li>    
    <li>4</li>    
</ul>

我认为通过以下方式很容易实现:$(".afterthis").after("</ul><h1>Title</h1><ul>");

但是它并没有关闭列表,而是移动了结束标签,插入了<h1>Title</h1><ul></ul>
要查看问题,请参见此jsfiddle链接:http://jsfiddle.net/Fx74b/14/
2个回答

4

Jquery只能与有效的HTML一起使用,而不能使用字符串部分。

因此,您不能将破碎的HTML传递给after()方法。

您需要自己拆分ul并在其中添加其他元素。

$(document).ready(function() {
    var splitelement = $(".afterthis"); // find the element which will be used for the split
    var ul = splitelement.parent(); // find the relative ul
    var newul = $('<ul>'); // create the new ul that will follow the existing one

    newul.append( splitelement.nextAll() ); // move the rest of the li elements to the new ul
    ul.after("<h1>Title</h1>").next().after(newul); // insert the title and then then ul
});

demo http://jsfiddle.net/gaby/ph5UM/


1
据我所知,.after 需要一个适当的 DOM 文本或对象作为参数。
$(</ul><h1>Title</h1><ul>) 从一个结束标签开始,因此 </ul> 被忽略了。 <ul> 没有完成,因此 jQuery 添加了一个结束标签 </ul>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接