例如,我需要获取所有 div 的 data-id
,并在 data- 之间放置一个带有
和 data-id="6"
的新 div id="3"data-id="9"
。
新的data-id也可以id为1,所以前面没有div,但是需要在data-id 2
之前(如果存在,如果不存在则在之前)下一个最高的数字)
示例:
<div class="container">
<div data-id="1"></div>
<div data-id="2"></div>
<div data-id="5"></div>
<div data-id="7"></div>
<div data-id="11"></div>
</div>
我需要在 7 到 11 之间添加一个 data-id="9"
的 div。
我还在学习 jQuery,所以我真的不知道如何实现它。我尝试使用 insertBefore()
但它没有像我想要的那样工作。仅当新的 div 为 data-id="10"
且容器中存在 data-id="11"
时才有效。
Jsfiddle
最佳答案
var $container = $('.container'),
$d = $container.find('div'),
$n = $('<div>', { data: { id: 9 }, text: 9 });
// filter the element with smaller data-id
var $a = $d.filter(function () {
return $(this).data('id') < 9;
}).last();
// If an element with smaller data-id exists
// insert the element after it
if ($a.length) $a.after($n);
// Otherwise prepend it to the container
else $container.prepend($n);
关于javascript - jQuery 将 div 放在两个不同的 div 之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19125757/