【问题标题】:Jquery Multiple Click EventsJquery 多次点击事件
【发布时间】:2016-07-22 13:46:41
【问题描述】:

我正在动态创建对象,这些对象在单击时构造视图并将事件绑定到构造的视图。但是,click 事件始终将自身附加到最后创建的对象。我确实希望每个对象都有相同的点击事件,但是我传递给新类的数据对于每个实例都是唯一的。

对象创建:

$.each(data,function(i,json)
        {
            var channelWrapper = new ChannelDisplayView(that.channelContainer, json);           
            that.channelContainer.append(channelWrapper.createView());
        });

ChannelDisplayView.js

function ChannelDisplayView(parent, data){
    this.parent = parent;
    this.data = data;
}
ChannelDisplayView.prototype.createView = function(){
    this.channelWrapper = $("<div/>").addClass("channelDisplay").attr("id", this.data.fullName);
    this.channelTitle = $("<div/>").addClass("channelTitle").html(this.data.fullName);
    this.channelSource = $("<div/>").addClass("sourceType").html(this.data.sourceType);
    this.channelWrapper.append(this.channelTitle);      
    this.channelWrapper.append(this.channelSource); 

    that = this;
    this.channelWrapper.unbind().on("click",function(event){
        ControllersSingleton.getInstance().getProgramController().setupPage(that.data);     
    });

    return this.channelWrapper;
}

如您所见,每个类都将保存自己的 JSON 数据,如果单击“div”,则应使用该数据传递给另一个控制器的实例。无论我点击哪个 div,发送的数据始终来自最后创建的对象。

我在这里遗漏了什么明显的东西吗?

【问题讨论】:

  • jsFiddle 或 jsBin 的任何机会?

标签: javascript jquery jquery-events


【解决方案1】:

您似乎创建了一个全局 that,在每次循环迭代中,它都被 that = this 覆盖。

不要在that.channelContainer 上调用append,而是尝试使用您创建的实例,例如channelWrapper.channelContainer.append...。 channelWrapper 的作用域是循环迭代。

【讨论】:

    【解决方案2】:

    您可以将事件处理程序绑定到整个文档并侦听特定类型的所有事件,如果事件目标与特定选择器匹配,则使用回调进行响应。例如:

    $(document).on('click', '.some-class', function(e){
      console.log('.some-class element clicked.');
    });
    

    该代码将监听对文档的任何点击,并且如果目标匹配第二个参数中的选择器,它将执行第三个参数中的回调函数。

    当我向 DOM 动态添加元素时,我经常发现最好使用这样的方法。

    【讨论】:

    • 我之前确实尝试过使用 ID,因为这是唯一唯一的东西,并且不知何故它仍然在命中最后一个事件。
    • @urnotsam 你有没有机会把你的代码放在 jsfiddle 或 codepen 中?
    • 我会尝试把一个放在一起
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多