jQuery的奇怪插入问题 [英] Weird insert problem with jQuery

查看:7
本文介绍了jQuery的奇怪插入问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,我不想通过 javascript 打断它以添加标题:

I got a list that i wan't to interrupt via javascript to add a title:

发件人:

<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>

but it doesn't close the list, it moves the end tag, it inserts <h1>Title</h1><ul></ul>

要查看问题,请参阅此 jsfiddle http://jsfiddle.net/Fx74b/14/

to see the problem see this jsfiddle http://jsfiddle.net/Fx74b/14/

推荐答案

Jquery 仅适用于有效的 HTML,而不适用于字符串部分.

Jquery works with valid HTML only, not string parts.

所以你不能将损坏的 html 传递给 after() 方法.

So you cannot pass broken html to the after() method.

您需要拆分自己的 ul 并在其间添加其他元素.

You will need to split the ul your self and add the other elements in between.

$(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
});

演示 http://jsfiddle.net/gaby/ph5UM/

这篇关于jQuery的奇怪插入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆