我可以使用jQuery $(document).on('each','。showComments',function(e){})

时间:2013-10-25 16:29:45

标签: javascript jquery html

我正在使用jquery UI对话框来显示注释或其他文本,具体取决于所点击的内容。

这是我的JSfiddle链接Dialog Demo

我使用过代码

$('.showComments').each(function () {
    var panel = $(this).parent().siblings('.divCommentDetail');
    $(this).click(function () {
        panel.dialog('open');
    });
});

$('.showContractChanges').each(function () {
    var panel = $(this).parent().siblings('.divContractChangeDetail');
    $(this).click(function () {
        panel.dialog('open');
    });
});


$(".divCommentDetail, .divContractChangeDetail").dialog({
    autoOpen: false,
    modal: true,
    open: function () {
        $(this).parent().siblings('.ui-dialog-titlebar').addClass('ui-state-error');
    },
    show: {
        effect: 'blind',
        duration: 1000
    },
    hide: {
        effect: 'explode',
        duration: 1000
    }
});

并在页面加载时动态添加内容。我正在尝试使用$(document).on('each','。showComments',function(e){});这样它就可以使用动态加载的内容,但它根本不起作用。这是我修改过的代码。

$(document).on('each', '.showComments', function () {
    var panel = $(this).parent().siblings('.divCommentDetail');
    $(this).click(function () {
        panel.dialog('open');
    });
});

但这根本不起作用。我做错了什么。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

如果在页面加载后动态添加.divContentDetail,则不是您需要更改的循环,而是您正在注册的事件:

$(document).on('click', '.showComments', function () {
  var panel = $(this).parent().siblings('.divCommentDetail');
  panel.dialog('open');
});

答案 1 :(得分:0)

.on绑定事件,它可以处理动态添加的元素。但是'each'不是一个事件,它是一种方法。

你应该像这样使用:

$(document).on('click', '.showComments', function () {
    var panel = $(this).parent().siblings('.divCommentDetail');


    panel.dialog('open');
});