簡體   English   中英

向動態創建的事件偵聽器添加參數

[英]Adding a Parameter to an Event Listener created Dynamically

我正在動態創建一系列按鈕。 如何將參數添加到事件偵聽器this.Purchase如下: this.Purchase(i) 簡單地添加“(i)”是行不通的。

      for (var i = 0; i < size; i++) {
         var button = document.createElement('input')
         button.setAttribute('type', 'submit')
         button.setAttribute('value', 'Purchase')
         button.addEventListener('click', this.Purchase)
      }

 var thing = { Purchase: function() { console.log(this.getAttribute('data-index')); } }; for (var i = 0; i < 3; i++) { var button = document.createElement('input'); button.setAttribute('type', 'submit'); button.setAttribute('value', 'Purchase'); button.setAttribute('data-index', i); button.addEventListener('click', thing.Purchase); document.body.appendChild(button); }

正如我在評論中提到的,將數據屬性與事件處理程序一起使用的示例。

為每個按鈕添加一個 data 屬性,並使用this關鍵字在 onclick 回調中調用購買函數:

 var size = 3 for (var i = 0; i < size; i++) { var button = document.createElement('input') button.setAttribute('type', 'submit') button.setAttribute('value', 'Purchase') button.dataset.idx = i button.addEventListener('click', function() { purchase(this.dataset.idx) }) document.body.appendChild(button) } function purchase(idx) { console.log(idx) }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM