1

I need to get for example all div's data-id's and place a new div with data-id="6" in between data-id="3" and data-id="9".

The new data-id can be with an id of 1 too, so there's no div before it, but it needs to be before data-id 2 (if it exists, if not then before the next highest number)

Example:

<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>

And I need to add a div with data-id="9" in between 7 and 11.

I'm still learning jQuery so I don't really have any clue how to achieve this. I tried with insertBefore() but it doesn't work like I want it to. It only works when the new div is data-id="10" and data-id="11" exists in the container.

Jsfiddle

http://jsfiddle.net/u3TH4/

4

2 回答 2

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

http://jsfiddle.net/mV9sw/

于 2013-10-01T21:03:51.727 回答
0

这是我想到的第一种方法:

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");
于 2013-10-01T21:11:52.983 回答