尝试使用jQuery向动态内容添加事件处理程序

Trying to add event handler to dynamic content using jQuery

本文关键字:添加 事件处理 程序 动态 jQuery      更新时间:2023-09-26

我试图添加一个onclick事件处理程序到复选框列表。它没有像我期望的那样提醒复选框ID(我正在点击的那个),而是总是提醒第3个复选框,不管我点击哪个。为什么会这样,我怎样才能让它像我想要的那样运行。当我点击复选框2时,我想让它提醒"2"…等。

function component (componentId, displayType, parentId) {
    this.componentId = componentId;
    this.parentId = parentId;
    this.displayType = displayType;
}
var components = [];
components.push(new component(0, null, null);
components.push(new component(1, null, null);
components.push(new component(2, null, null);
components.push(new component(3, null, null);

var arrayLength = components.length;
for (var i = 0; i < arrayLength; i++) {
    var component = components[i];
    jQuery('#questionnaireComponentId'+component.componentId).find('input:checkbox').click(
        function(){
            selectParentCheckbox(component.componentId);
            }
    );
}
function selectParentCheckbox(componentId){
    alert(componentId);
}

这是因为Javascript闭包。

应该在每次迭代时传递参数,而不是在迭代完成后才传递参数。

for (var i = 0; i < arrayLength; i++) {
    var component = components[i];
    jQuery('#questionnaireComponentId' + component.componentId)
      .find('input:checkbox')
      .click(selectParentCheckbox.bind(null, component.componentId));
}

bind函数允许您命名click事件将调用的函数以及应该传递给它的参数。


与问题无关,但仅供您参考:我认为您误解了jQuery及其事件委托的功能,因为您可以使用更好的方法。