jqueryui打开多个对话框;应该只打开一个

问题描述 投票:1回答:3

我有一个带有评论的供稿,并希望允许用户删除评论。下面的代码允许用户单击图像,并出现一个对话框,警告用户删除操作。

现在,这适用于页面上的每个注释,因此单击删除按钮可一次打开多个对话框(与注释一样多的对话框)。

如何更改下面的代码,以便在单击选择器时,仅显示该注释的对话框?

$('span.delete_comment_button img').click(function() { 
        $('.delete_comment_dialog').dialog('open'); 
        return false; 
});
jquery jquery-ui dialog
3个回答
3
投票

首先,页面上不应有多个#delete_comment_dialog元素,因此我们将其更改为.delete_comment_dialog。然后,您可以将整个类添加到注释中,使用closest转到顶级注释包装器,然后使用closest返回到对话框。 HTML看起来像这样:

find

和您的jQuery这样:

find

演示:<div class="comment"> blah blah blah blah <span class="delete_comment_button">delete</span> <div class="delete_comment_dialog">first dialog</div> </div> <div class="comment"> blah blah blah blah <span class="delete_comment_button">delete</span> <div class="delete_comment_dialog">second dialog</div> </div>​

或者,使用具有$('span.delete_comment_button').click(function() { $(this).closest('.comment') .find('.delete_comment_dialog') .dialog('open'); return false; });​ 属性的单个对话框,将http://jsfiddle.net/ambiguous/VePZp/添加到注释id中,然后将注释的id传递通过<div>属性或类似属性进行删除。例如:

id

和:

data

演示:<div id="cmt1" class="comment"> blah blah blah blah <span class="delete_comment_button">delete</span> </div> <div id="cmt2" class="comment"> blah blah blah blah <span class="delete_comment_button">delete</span> </div> <div id="delete_comment_dialog">the only dialog</div>


1
投票

您还可以为每个图像和对话框指定一个特定的ID,以便更好地定位每个图像。由于您已经遍历了注释,因此可以仅添加循环的索引,否则可以使用随机数:

$('#delete_comment_dialog').dialog({
    autoOpen: false,
    close: function() {
        // 'close' handler just for demonstration purposes.
        alert($('#delete_comment_dialog').data('kill-this'));
    }
});
$('span.delete_comment_button').click(function() {
    var $cmt = $(this).closest('.comment');
    $('#delete_comment_dialog').data('kill-this', $cmt[0].id);
    $('#delete_comment_dialog').dialog('open');
    return false; 
});​

您的jquery将会是

http://jsfiddle.net/ambiguous/M4QM6/

理想情况下,您希望将ID以外的其他内容用于索引存储,因为ID不应仅包含数字。

您可能还可以将$ .each函数与return false一起使用。如果在$ .each循环中包含return false,则它应在1次迭代后停止,并且仅打开1个对话框。


0
投票

我尝试了以下代码,但结果是我可以多次打开对话框...为什么?有人可以帮助我吗?

<span class="delete_comment_button"><img id="1" /></span>
<div id="delete_comment_dialog1"></div>
© www.soinside.com 2019 - 2024. All rights reserved.