2

我有多个具有相同类名的 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 容器中删除类“cancel”。

<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 在索引之外。我希望这是有道理的,再次感谢您。

4

1 回答 1

0

我会重组你的代码。这是我想出的框架。我认为您可以利用它来满足您的需求。

http://jsfiddle.net/v4dtL/

一些东西:

不要使用live. 它已被弃用。使用ondelegate代替。

向单击的元素添加一个名为 modalized 的类。这使您可以跟踪谁启动了模式窗口,而无需进行任何时髦的 DOM 遍历。

使用 jQueryindex找出被点击元素相对于其兄弟元素的索引。

//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');
});
于 2012-11-28T02:08:49.310 回答