Javascript jQuery将div放在两个不同的div之间

Javascript jQuery将div放在两个不同的div之间,javascript,jquery,html,Javascript,Jquery,Html,例如,我需要获取所有div的数据id,并在数据id=3和数据id=9之间放置一个数据id=6的新div 新的数据id也可以是id为1的,因此它前面没有div,但如果它存在,则必须在数据id 2之前,如果不存在,则必须在下一个最大数字之前 例子: 我需要在7和11之间添加一个数据id=9的div 我还在学习jQuery,所以我真的不知道如何实现这一点。我以前尝试过InsertName,但它不能像我希望的那样工作。仅当容器中存在新的div为data id=10且data id=11时,它才起作用 J

例如,我需要获取所有div的数据id,并在数据id=3和数据id=9之间放置一个数据id=6的新div

新的数据id也可以是id为1的,因此它前面没有div,但如果它存在,则必须在数据id 2之前,如果不存在,则必须在下一个最大数字之前

例子: 我需要在7和11之间添加一个数据id=9的div

我还在学习jQuery,所以我真的不知道如何实现这一点。我以前尝试过InsertName,但它不能像我希望的那样工作。仅当容器中存在新的div为data id=10且data id=11时,它才起作用

JSFIDLE
首先想到的是:

function addDiv(id, content) {
    var $newDiv = $("<div></div>").attr("data-id",id).html(content),
        $container = $("div.container"),
        $divs = $container.find("div[data-id]"),
        inserted = false;
    $divs.each(function(i) {
        if (id < +$(this).attr("data-id")){
            $newDiv.insertBefore(this);
            inserted = true;
            return false;
        }
    });
    if (!inserted)
        $newDiv.appendTo($container);
}

addDiv(9,"whatever");

这应该给你一个如何进行的想法:标准/模式是什么?你只是想做一个随机插入?@PSL实际上我有一个拖放操作,如果我把一个盒子拖到容器中,它需要在正确的位置。@KristjanKirpu那么你知道在哪个div之后需要插入吗?如果您知道使用sourceElem.AfterElementToBeInSerted插入此div,是否可以设置一个最小/,或类似值,以显示正在使用的内容?
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);
function addDiv(id, content) {
    var $newDiv = $("<div></div>").attr("data-id",id).html(content),
        $container = $("div.container"),
        $divs = $container.find("div[data-id]"),
        inserted = false;
    $divs.each(function(i) {
        if (id < +$(this).attr("data-id")){
            $newDiv.insertBefore(this);
            inserted = true;
            return false;
        }
    });
    if (!inserted)
        $newDiv.appendTo($container);
}

addDiv(9,"whatever");