Weird insert problem with jQuery

左心房为你撑大大i 提交于 2019-12-20 00:54:14

问题


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

From:

<ul>
    <li>1</li>
    <li class="afterthis">2</li>
    <li>3</li>
    <li>4</li>
</ul>

To:

<ul>
    <li>1</li>
    <li class="afterthis">2</li>
</ul>
<h1>Title</h1>
<ul>
    <li>3</li>    
    <li>4</li>    
</ul>

i thought that was easy by doing: $(".afterthis").after("</ul><h1>Title</h1><ul>");

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

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


回答1:


Jquery works with valid HTML only, not string parts.

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

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

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




回答2:


As far as I know .after needs an argument which is a proper DOM text or object.
$(</ul><h1>Title</h1><ul>) is started from an end tag so </ul> is ignored. <ul> is not finished to jquery added an end tag for <ul>



来源:https://stackoverflow.com/questions/6069217/weird-insert-problem-with-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!