3

I am implementing a jquery function which is able to insert a div in the right place depending on the existing dom structure

The case of existing dom structure are the following

<!-- case 1 -->
<div class='container'>
   <div class='foo'></div>
   <div class='bar'>last bar</div>
   <div class='bar'>some bar</div>
   <div class='bar'>first bar</div>
</div>

<!-- case 2 -->
<div class='container'>
   <div class='bar'>last bar</div>
   <div class='bar'>some bar</div>
   <div class='bar'>first bar</div>
</div>


<!-- case 3 -->
<div class='container'>
</div>

In every 3 cases, it should add a new <div class='bar'></div> inside container but before the first <div class='bar'></div>

here is the code which works for the case 1 and 2 but not for the 3.

var last_bar = $('<div>').addClass('bar').text('last bar');
$($('.container').find('.bar')[0]).prepend(last_bar)​;

​</p>

Any hints how to make this code more general?

here is the demo http://jsfiddle.net/3wFda/

4

4 回答 4

1

这只是我,但我喜欢用这样的新函数包装东西......

$.fn.addBar = function() {
    $(this).each(function() {
        var $last_bar = $('<div>').addClass('bar').text('last bar');
        if ($(this).find(".bar").length == 0) {
            $(this).append($last_bar);
        } else {
            $(this).find('.bar:first').prepend($last_bar); 
        }
    });
};

然后你就这样称呼它...

​$(".container").addBar();​​​​​

这是一个更新的 jsfiddle http://jsfiddle.net/3wFda/2/

于 2012-10-22T13:09:28.920 回答
1

尝试这个:

var last_bar = $('<div>').addClass('bar').text('last bar');
$($('.container').find('.bar')[0] || $('.container')).prepend(last_bar);​
于 2012-10-22T13:03:34.037 回答
0

你可以这样做,

var last_bar = $('<div>').addClass('bar').text('last bar');
$('.container .bar:eq(0), .container:empty').prepend(last_bar);​
于 2012-10-22T13:02:32.460 回答
0
$('.container').find('.bar:first').prepend(...)

编辑您的案例 3 需要一些额外的工作。

var $c = $('.container');
if($c.contains('.bar').length) {
    $c.find('.bar:first').prepend(...)
} else {
    $c.append(...)
}
于 2012-10-22T12:59:38.170 回答