簡體   English   中英

使用for循環並傳遞不同的參數將事件偵聽器添加到多個元素

[英]Adding event listener to multiple elements using for loop and passing different parameters

<div id="mydiv0"></div>
<div id="mydiv1"></div>
<div id="mydiv2"></div>


var myArray = [
  document.getElementById("mydiv0"),
  document.getElementById("mydiv1"),
  document.getElementById("mydiv2")
];

function myFunction(x){
  alert("my number is " + x);
}

for(var i = 0; i < myArray.length; i++){
  myArray[i].addEventListener("click", function(){myFunction(i);});
}

我想將事件偵聽器附加到myArray中的每個元素。 單擊時,將顯示一條警告消息,分別顯示mydiv0,mydiv1和mydiv2的數字0、1和2。 如上例所示,我嘗試使用for循環,但是無論我單擊哪個div,都會收到“我的號碼為3”的消息。 有沒有辦法將變量i的不同值作為myFunction的參數傳遞?

您可以簡單地在循環中使用let而不是var聲明變量,以創建塊作用域局部變量。

 var myArray = [ document.getElementById("mydiv0"), document.getElementById("mydiv1"), document.getElementById("mydiv2") ]; function myFunction(x){ alert("my number is " + x); } for(let i = 0; i < myArray.length; i++){ myArray[i].addEventListener("click", function(){myFunction(i);}); } 
 <div id="mydiv0">Div 0</div> <div id="mydiv1">Div 1</div> <div id="mydiv2">Div 2</div> 

您必須為點擊回調創建一個隔離范圍。

for(var i = 0; i < myArray.length; i++){
  (function(i){
    myArray[i].addEventListener("click", function(){myFunction(i);});
  })(i);
}

使用bind

 var myArray = [ document.getElementById("mydiv0"), document.getElementById("mydiv1"), document.getElementById("mydiv2") ]; function myFunction(x){ alert("my number is " + x); } for(var i = 0; i < myArray.length; i++){ myArray[i].addEventListener("click", myFunction.bind(null, i)); } 
 div { height: 20px; width: 200px; border: 1px solid black; } 
 <div id="mydiv0"></div> <div id="mydiv1"></div> <div id="mydiv2"></div> 

另外,您可以如下使用data屬性。

<div id="mydiv0" data-value="1"></div>
<div id="mydiv1" data-value="2"></div>
<div id="mydiv2" data-value="3"></div>

for(var i = 0; i < myArray.length; i++){
    myArray[i].addEventListener("click",  function() {
        myFunction(this.getAttribute('data-value'));
    });
}

只需使用“ let”而不是“ var”,如下所示:

for(let i = 0; i < myArray.length; i++){
    myArray[i].addEventListener("click", function(){myFunction(i);});
}

'let'允許您聲明變量,其作用域僅限於使用它的塊,語句或表達式。 這與'var'關鍵字不同,該關鍵字在全局范圍內或整個函數本地定義變量,而與塊范圍無關。

難以將唯一的事件偵聽器添加到已創建的<div>通過 for 循環的元素</div><div id="text_translate"><p>我正在做一個項目來學習一些 JavaScript,目標是在單頁 web 應用程序中動態提供電子郵件。 應用程序的HTML已經使用createElement JS方法創建。 到目前為止,我已經成功地顯示了包含所有電子郵件的“收件箱”頁面,如下圖所示:</p><p> <a href="https://i.stack.imgur.com/V8cZq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V8cZq.png" alt=""></a></p><p> 我目前正在嘗試通過使用 addEventListener 使這些單獨的電子郵件中的每一個都可以點擊。 我遇到的問題是,每當我單擊任何一封電子郵件時,都會呈現收件箱中的第一個 email(id:1,主題:測試電子郵件),並且無法查看任何其他電子郵件。</p><p> <a href="https://i.stack.imgur.com/BBjQj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BBjQj.png" alt=""></a></p><p> 我可以看到相同的 email.id 被應用到所有創建的 div 的事件偵聽器,盡管所有 div 都被正確創建,並包含來自相應電子郵件的所有信息。</p><p> 這是加載郵箱 JS,它呈現收件箱中的所有電子郵件:</p><pre> function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'block'; document.querySelector('#compose-view').style.display = 'none'; document.querySelector('#single-view').style.display = 'none'; // Show the mailbox name document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`; // GET request fetch(`/emails/${mailbox}`).then(response => response.json()).then(emails => { // Print emails to console console.log(emails); // Iterate through each email for(var i = 0; i < emails.length; i++) { var email = emails[i]; // Create div and append email content to HTML var emaildiv = document.createElement('div'); emaildiv.style.borderStyle = 'solid'; emaildiv.style.borderColor = 'black'; emaildiv.style.borderWidth = '0.1rem'; emaildiv.style.borderRadius = '0'; emaildiv.style.marginBottom = '0.2rem'; emaildiv.style.padding = '0.3rem'; emaildiv.innerHTML = `<b>${email.sender}</b> --- ${email.subject}<br>${email.timestamp}`; // If individual email selected then view email emaildiv.addEventListener('click', () => view_email(email)); // Populate div HTML with emails document.querySelector('#emails-view').append(emaildiv); console.log(email.read); // Colour backgrounds based on whether emails have been read if (email.read == true) { emaildiv.style.backgroundColor = 'lightgrey'; } console.log(email); } });}</pre><p> 這是視圖 email JS,它應該渲染個人 email 的 HTML:</p><pre> // View email function view_email(email) { console.log(email.id); // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'none'; document.querySelector('#single-view').style.display = 'block'; // GET request fetch(`/emails/${email["id"]}`).then(response => response.json()).then(email => { // Create div, set class, and append email content to HTML var reademail = document.createElement('div'); reademail.innerHTML = ''; reademail.style.borderStyle = 'solid'; reademail.style.borderColor = 'black'; reademail.style.borderWidth = '0.1rem'; reademail.style.borderRadius = '0'; reademail.style.marginBottom = '0.2rem'; reademail.style.padding = '0.3rem'; reademail.innerHTML = ` <b>From:</b> ${email.sender}<br> <b>To:</b> ${email.recipients}<br> <b>Subject:</b> ${email.subject}<br> <b>Timestamp:</b> ${email.timestamp}<br> <button class="btn btn-sm btn-outline-primary" id="Reply">Reply</button> <hr> ${email.body}`; // Populate div HTML with emails document.querySelector('#single-view').append(reademail); // Mark unread emails as read if (email.read === 'false') { fetch(`/emails/${email}`, { method: 'PUT', body: JSON.stringify({ read: true }) }) } }); }</pre><p> 這是存儲在 email GET 響應中的示例(虛擬數據):</p><pre> { "id": 1, "sender": "user@example.com", "recipients": ["user@example.com"], "subject": "Hello,": "body", "Hello, world:", "timestamp": "Oct 24 2020, 12:00 AM", "read": false, "archived": false }</pre><p> 我已經嘗試將其他每封電子郵件的 ID 硬編碼到視圖 email JS 中,並且可以看到該功能按要求工作(顯示電子郵件)。</p><p> 因此,我知道問題與上面的加載郵箱 JS 有關,並且可能與事件偵聽器如何在 for 循環中應用有關。 如果有人可以闡明如何將唯一的事件偵聽器應用於每個單獨的 div,將不勝感激。</p><p> 謝謝!</p></div>

[英]Difficulty adding unique event listener to created <div> elements via a for loop

暫無
暫無

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

相關問題 將相同的事件偵聽器添加到具有不同參數的多個元素 單擊另一個循環時將事件偵聽器添加到元素 將相同的事件偵聽器添加到多個元素 在js中向多個select元素添加事件監聽器 使用“ for”循環添加“ click”事件監聽器 難以將唯一的事件偵聽器添加到已創建的<div>通過 for 循環的元素</div><div id="text_translate"><p>我正在做一個項目來學習一些 JavaScript,目標是在單頁 web 應用程序中動態提供電子郵件。 應用程序的HTML已經使用createElement JS方法創建。 到目前為止,我已經成功地顯示了包含所有電子郵件的“收件箱”頁面,如下圖所示:</p><p> <a href="https://i.stack.imgur.com/V8cZq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V8cZq.png" alt=""></a></p><p> 我目前正在嘗試通過使用 addEventListener 使這些單獨的電子郵件中的每一個都可以點擊。 我遇到的問題是,每當我單擊任何一封電子郵件時,都會呈現收件箱中的第一個 email(id:1,主題:測試電子郵件),並且無法查看任何其他電子郵件。</p><p> <a href="https://i.stack.imgur.com/BBjQj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BBjQj.png" alt=""></a></p><p> 我可以看到相同的 email.id 被應用到所有創建的 div 的事件偵聽器,盡管所有 div 都被正確創建,並包含來自相應電子郵件的所有信息。</p><p> 這是加載郵箱 JS,它呈現收件箱中的所有電子郵件:</p><pre> function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'block'; document.querySelector('#compose-view').style.display = 'none'; document.querySelector('#single-view').style.display = 'none'; // Show the mailbox name document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`; // GET request fetch(`/emails/${mailbox}`).then(response => response.json()).then(emails => { // Print emails to console console.log(emails); // Iterate through each email for(var i = 0; i < emails.length; i++) { var email = emails[i]; // Create div and append email content to HTML var emaildiv = document.createElement('div'); emaildiv.style.borderStyle = 'solid'; emaildiv.style.borderColor = 'black'; emaildiv.style.borderWidth = '0.1rem'; emaildiv.style.borderRadius = '0'; emaildiv.style.marginBottom = '0.2rem'; emaildiv.style.padding = '0.3rem'; emaildiv.innerHTML = `<b>${email.sender}</b> --- ${email.subject}<br>${email.timestamp}`; // If individual email selected then view email emaildiv.addEventListener('click', () => view_email(email)); // Populate div HTML with emails document.querySelector('#emails-view').append(emaildiv); console.log(email.read); // Colour backgrounds based on whether emails have been read if (email.read == true) { emaildiv.style.backgroundColor = 'lightgrey'; } console.log(email); } });}</pre><p> 這是視圖 email JS,它應該渲染個人 email 的 HTML:</p><pre> // View email function view_email(email) { console.log(email.id); // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'none'; document.querySelector('#single-view').style.display = 'block'; // GET request fetch(`/emails/${email["id"]}`).then(response => response.json()).then(email => { // Create div, set class, and append email content to HTML var reademail = document.createElement('div'); reademail.innerHTML = ''; reademail.style.borderStyle = 'solid'; reademail.style.borderColor = 'black'; reademail.style.borderWidth = '0.1rem'; reademail.style.borderRadius = '0'; reademail.style.marginBottom = '0.2rem'; reademail.style.padding = '0.3rem'; reademail.innerHTML = ` <b>From:</b> ${email.sender}<br> <b>To:</b> ${email.recipients}<br> <b>Subject:</b> ${email.subject}<br> <b>Timestamp:</b> ${email.timestamp}<br> <button class="btn btn-sm btn-outline-primary" id="Reply">Reply</button> <hr> ${email.body}`; // Populate div HTML with emails document.querySelector('#single-view').append(reademail); // Mark unread emails as read if (email.read === 'false') { fetch(`/emails/${email}`, { method: 'PUT', body: JSON.stringify({ read: true }) }) } }); }</pre><p> 這是存儲在 email GET 響應中的示例(虛擬數據):</p><pre> { "id": 1, "sender": "user@example.com", "recipients": ["user@example.com"], "subject": "Hello,": "body", "Hello, world:", "timestamp": "Oct 24 2020, 12:00 AM", "read": false, "archived": false }</pre><p> 我已經嘗試將其他每封電子郵件的 ID 硬編碼到視圖 email JS 中,並且可以看到該功能按要求工作(顯示電子郵件)。</p><p> 因此,我知道問題與上面的加載郵箱 JS 有關,並且可能與事件偵聽器如何在 for 循環中應用有關。 如果有人可以闡明如何將唯一的事件偵聽器應用於每個單獨的 div,將不勝感激。</p><p> 謝謝!</p></div> 將點擊事件分配給具有不同參數的多個元素 動態js畫布將事件偵聽器添加到for循環中的多個點 "將多個變量傳遞給事件監聽器" 通過原生JavaScript傳遞事件偵聽器參數?
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM