2016-07-22 123 views
0

我動態創建構建視圖的對象,並在單擊時將事件綁定到構造視圖。但是,click事件總是將自己附加到最後創建的對象。我確實希望每個對象具有相同的單擊事件,但傳遞給新類的數據每個實例都是唯一的。Jquery多個點擊事件

創建對象:

$.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是否始終來自上次創建的對象,都會發送數據。

我在這裏錯過了一些明顯的東西嗎?

+0

jsFiddle或jsBin的機會嗎? – noitse

回答

0

您可以將事件處理程序綁定到整個文檔,並偵聽某個特定類型的所有事件,如果事件目標匹配某個選擇器,則使用回調進行響應。例如:

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

該代碼將偵聽該文件的任何點擊,並如果目標在第二個參數選擇相匹配,它會在第三個參數執行回調函數。

當我向DOM動態添加元素時,我經常發現最好使用這樣的方法。

+0

我之前使用過ID做過這個嘗試,因爲那是唯一的唯一東西,不知何故它仍然是最後一個事件。 – urnotsam

+0

@urnotsam你有可能把你的代碼放在jsfiddle或codepen中嗎? – LGFaler

+0

我會盡量一起扔 – urnotsam

0

它看起來像你已經創建了一個全球that在每個循環迭代正在覆蓋that = this

而不是調用that.channelContainer附加嘗試使用您創建的實例,如channelWrapper.channelContainer.append...。 channelWrapper的作用域爲循環迭代。