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

我正在使用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'); }); }); 

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

谢谢您的帮助。

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

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

.on绑定事件,用于动态添加元素。 但'each'不是一个事件,它是一种方法。

你应该这样使用:

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