我正在尝试在第二个列表项之后插入一个新的 div。但我也想关闭</ol>
在它之前打开一个新的 <ol>
就在它之后。
这个:
<ol>
<li>test 1</li>
<li>test 2</li>
<li>test 3</li>
<li>test 4</li>
</ol>
应该变成这样:
<ol>
<li>test 1</li>
<li>test 2</li>
</ol>
<div>NEW DIV</div>
<ol>
<li>test 3</li>
<li>test 4</li>
</ol>
jQuery:
var el = $('ol li:eq(1)');
el.after('<div>NEW DIV</div>');
这是我的演示:http://jsfiddle.net/5hhr2/
有什么方法可以用 jQuery 做到这一点吗?
我已经尝试过 after('</ol><div>NEW DIV</div><ol>)
但这显然行不通,正如这里讨论的那样:Using .after() to add html closing and open tags .
最佳答案
尝试
var $lis = $('ol li');
$lis.filter(':lt(2)').unwrap().wrapAll('<ol/>').closest('ol').after('<div>NEW DIV</div>');
$lis.filter(':gt(1)').wrapAll('<ol/>');
<强> Fiddle
如果你想链接所有这些,那么:
var $lis = $('ol li');
$lis.filter(':lt(2)') //get all the li's with index less than 2 i.e your number
.unwrap() //unwrap it
.wrapAll('<ol/>') //wrap them in ol
.closest('ol').after('<div>NEW DIV</div>').end().end() //append div next to the ol and go back in the chain to the first list of li's
.filter(':gt(1)') //filter to get remaining items
.wrapAll('<ol/>'); //wrap them all in a new ol
<强> Fiddle
关于javascript - 如何在有序列表之间插入新的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19067949/