奇怪的插入问题与jQuery [英] Weird insert problem with jQuery
问题描述
我得到了我wan't通过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)后(&LT; / UL&GT;&LT; H1&GT;标题&LT; / H1&GT;&LT; UL&gt;中);
但它并没有关闭列表,它的动作结束标签,它插入&LT; H1&GT;标题&LT; / H1&GT;&LT; UL&GT;&LT; / UL&GT;
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传递给后()
方法。
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屋!