从兄弟元素onClick jquery中查找索引

时间:2012-11-28 01:54:38

标签: jquery indexing css-selectors

我有多个具有相同类名的div,可以动态填充容器。

<div class="container">
<div class="content cancel"><button class="showModal"></button></div>
<div class="content cancel"><button class="showModal"></button></div>
<div class="content cancel"><button class="showModal"></button></div>
<div class="content cancel"><button class="showModal"></button></div>
<div class="content cancel"><button class="showModal"></button></div>
</div>

每个div.content都有一个显示jqueryUI对话框的按钮。启动模态后,它有两个用于保存和取消的按钮。如果单击取消,则警报将显示启动模式的div的索引位置,并从启动它的div.content容器中删除“取消”类。

<div class="modal">
<button class="save">save</button>
<button class="RemoveCancel">cancel</button>
</div>

这是我的Jquery

$(".modal").on("click", ".RemoveCancel", function () {

    var parent = $(this).closest(".content");
    var modalTest = $(".content").index(parent);
    $("div.content:nth-child(" + (modalTest + 1) + ")").removeClass("cancel");
    alert("div.content:nth-child(" + (modalTest + 1) + ")");
});

和模态

$(function () {
    $(".modal").dialog({
        autoOpen: false,
        height: 140,
        modal: true
    });

 $(".showModal").live('click', function () {
        $(".modal").dialog("open");
        return false;
    });

    $(".save, .RemoveCancel").live('click', function () {
        $(".modal").dialog("close");
        return false;
    });
});

感谢任何输入,目前我获得了警报的-1值。如果我省略索引的选择器,它将显示但是许多div是索引的一部分。我希望这是有道理的,再次感谢你。

1 个答案:

答案 0 :(得分:0)

我会重构您的代码。这是我提出的框架。我认为您可以根据自己的需要利用它。

http://jsfiddle.net/v4dtL/

一些事情:

请勿使用live。它已被弃用。请改用ondelegate

将一个名为modalized的类添加到单击的元素中。这使您可以跟踪谁启动模态窗口而不进行任何时髦的DOM遍历。

使用jQuery的index找出与其兄弟姐妹相关的被点击元素的索引。

//when showmodal is clicked, add modalized class to the clicked element
$(".container").on('click', '.showModal', function() {
    $(".modal").show();
    $(this).addClass('modalized');
});

//I broke save and removecancel into separate event handlers so that they don't step on each others toes (order of operations)
$(".modal").on('click', '.save', function() {
    $(".modal").hide();
    $('.modalized').removeClass('modalized');
});

//Use Index() to find the modalized element in relation to its siblings
$(".modal").on("click", ".RemoveCancel", function() {        
    var index = $('.showModal').index($('.modalized'));
    alert(index);
    $(".modal").hide();    
    $('.modalized').removeClass('modalized');
});

​

jQuery的data对象允许您存储元素的信息。所以你可以这样做。未经测试。

$('.showModal').click( function() {
      //store clicked index
      var index = $(this).siblings().index($(this));
      $('.modal').show().data('clickedIndex', index);
});

$('.cancel').click( function() {
      //retrieve clicked index
      var index = $(this).closest('.modal').data('clickedIndex');
      alert(index);
      //get all showmodal buttons, but grab the one with matching index
      $('.showModal')[index].removeClass('foo');
});
相关问题