簡體   English   中英

將事件偵聽器添加到動態創建的div,並將其傳遞給它

[英]Adding an event listener to a dynamically created div, and passing this to it

我發現了有關傳遞變量的類似問題,但沒有關於傳遞變量的問題。

我試圖基於輸入到窗體創建一個div,然后附加一個事件偵聽器,該偵聽器調用一個要求將此事件傳遞給它的事件。 我已經到了創建div的地步,並根據輸入的數據添加了內容。 因此,現在我嘗試使用.addEventListener添加onClick事件,但看來您無法通過匿名函數傳遞它。 這是我正在嘗試的代碼。

  element.addEventListener("click", function(this){selectActiveCompetitor(this)});

sekectActiveCompetitor依賴於此傳遞給它,因此它可以定位正確的div

有什么解決辦法嗎?

除了上面我的評論,這是一個自動訪問我所說的this關鍵字的示例。 單擊任何按鈕將導致該特定按鈕上的文本被警告。

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}

function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    forEachNode( allByTag('button'), function(curNode, curIndex, nodeList){ curNode.addEventListener('click', onBtnClick, false); } );
}
/*
// expanded version of the above function
//
function onDocLoaded()
{
    var btns = allByTag('button');
    forEachNode(btns, attachBtnHandler);

    function attachBtnHandler(curNode, curIndex, nodeList)
    { 
        curNode.addEventListener('click', onBtnClick, false); 
    } 
}
*/


function onBtnClick(evt)
{
    alert(this.textContent);
}
</script>
<style>
</style>
</head>
<body>
    <button>This is btn1</button>
    <button>This is btn2</button>
    <button>This is btn3</button>
</body>
</html>

難以將唯一的事件偵聽器添加到已創建的<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.

相關問題 向動態創建的事件偵聽器添加參數 將事件偵聽器添加到動態創建的 div 動態添加事件監聽器 如何在具有交互式內容的動態創建的 div 上添加事件偵聽器 難以將唯一的事件偵聽器添加到已創建的<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> 動態創建按鈕的事件監聽器 動態創建的 html 的事件監聽器 在html中動態添加事件監聽器 在動態創建的元素上添加事件偵聽器 將事件偵聽器添加到動態創建的元素
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM