addeventlistener 相关问题

一种DOM事件方法,用于将事件侦听器添加到给定的DOM节点

当元素的innerHTML发生变化时触发函数?

我想在 div 元素的 innerHTML 更改时触发一个函数。 已使用 element.addEventListener('DOMCharacterDataModified', myFunction()); 进行测试但它似乎不能正常工作。它

回答 3 投票 0

在 div 中的 insideHTML 的每次更改中添加事件监听器

只是出于好奇,我想每次向这样的 div 添加 html 代码时都会收到一个事件 常量 xData = 40; const container = document.querySelector('.container'); 容器.innerHTML = ` 只是出于好奇,我想每次向这样的 div 添加 html 代码时都会收到一个事件 const xData = 40; const container = document.querySelector('.container'); container.innerHTML = `<div class="container_Addons">${xData}</div>`; container.addEventListener('i dont know',function(){ console.log("you have just added some exotic stuff!"); }); for (i= 0; i<10;i++){ container.innerHTML += `<div class="container_Addons">${i}st ${xData}</div>`; }; 每次添加 html 代码时让侦听器工作 使用 MutationObserver 可以很容易地观察元素的 childList 变化: // Utility functions: const el = (sel, par) => (par ||document).querySelector(sel); const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop); const repeat = (n, cb) => [...Array(n)].forEach((_, i) => cb(i)); // Task: watch content changes: const xData = 40; const container = el('.container'); const observeInsertion = new MutationObserver((records, observer) => { records.forEach(rec => { rec.addedNodes.forEach(node => { console.log(`Added some exotic stuff: ${node.textContent}`); }) }); }); observeInsertion.observe(container, { childList: true }); repeat(10, i => { const elAddon = elNew("div", { className: "container_Addons", textContent: `${i}st ${xData}`, }); container.append(elAddon); }); <div class="container"></div> innerHTML 不断更改元素的完整内容,因此我选择了更合适的 Element.append() 方法 - 以便仅收到关于某个特定子插入的通知。您也可以使用 .innerHTML = 代替 .append(),但在这种情况下,您将不得不做额外的无用且复杂的工作来检测到底是 new 插入的内容。 您可以使用 MutationObserver 和 childList: true 来订阅特定的 DOM 更改: const content = document.querySelector('#content'); const observer = new MutationObserver((mutationsList, observer) => { console.log(`innerHTML updated, ${ mutationsList.length } mutation${ mutationsList.length > 1 ? 's' : '' }`); }); observer.observe(content, { childList: true }); for (let i = 0; i < 10; ++i){ content.innerHTML += `<p>New element ${ i }</p>`; }; setTimeout(() => { content.innerHTML += `<p>Added from setTimeout()</p>`; }) setTimeout(() => { content.innerHTML += `<p>Added after 5 seconds</p>`; }, 5000) #content { padding-bottom: 67px; } #content > p { display: flex; align-items: center; justify-content: center; height: 100px; margin: 0; background: cyan; font-family: monospace; font-size: 32px; } #content > p + p { margin: 8px 0 0; } <div id="content"> <p>0</p> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <p>6</p> <p>7</p> <p>8</p> <p>9</p> </div> 但是请注意,您的 MutationObserver 的回调不会为执行更新 .innerHTML 的每个语句调用(因为它们可能会导致单次绘制,就像上面示例中 for 内的那些一样) ),但你可以从mutationsList获取更新元素的列表。 但是,如果在不同时间点添加新元素(如setTimeout中的元素),则每次更新都会调用您的回调。

回答 2 投票 0

触发addEventListener后如何停止链?

所以我有一个 addEventListener 函数,当单击它时,它将在两个不同的按钮中触发 addEventListener 。当单击第一个按钮时,它将插入玩家 1 文本或第二个按钮...

回答 1 投票 0

事件监听器在外部文件中设置后不起作用

当我尝试为创建的 DOM 元素设置事件侦听器,并将它们添加到元素列表中时,事件侦听器仍然存在于 JS 中,但是当我将它们添加到在 HTML 中创建的静态 DOM 元素时,他们不同意...

回答 0 投票 0

javascript中列表元素的点击事件

我正在做一个待办事项应用程序。我的 html 端有一个 ul,我正在将带有 javascript 的列表添加到这个无序列表中。我的目标是当我第一次点击任何待办事项时,这应该是直线风格并且......

回答 1 投票 0

退出包含事件监听器的函数

我对 Web 开发还是有点陌生,我正在开发一个使用 HTML 和 JavaScript 的项目。这是我遇到的问题。 随机标题 我对 Web 开发还是有点陌生,我正在开发一个使用 HTML 和 JavaScript 的项目。这是我遇到的问题。 <body> <h1>random heading</h1> <button id="clickme">clickme</button> <p id="yes"></p> <p id="no"></p> <script> const clickme = document.querySelector('#clickme') const yes = document.querySelector('#yes') const no = document.querySelector('#no') let yesScore = 0; let noScore = 0; function game() { clickme.addEventListener('click', myFunction); function myFunction(){ let promptVar = prompt('y/n'); if(promptVar === 'y') yes.textContent = ++yesScore; else if(promptVar === 'n') no.textContent = ++noScore; else return; if(yesScore + noScore === 5){ console.log('over'); } } } </script> </body> 所以我的问题是,我希望 game() 函数在 (yesScore + noScore === 5) 时退出,但是如果我在 if 语句中使用 return 或 break,它只会退出 myFunction() 函数. 我尝试过在console.log('over')之后使用标签直接跳出函数到game()函数之外,却发现标签不能跨越函数边界。 我猜你想在游戏结束时删除 onclick 事件你可以在这个例子中使用removeEventListener。所以这是代码: <body> <h1>random heading</h1> <button id="clickme">clickme</button> <p id="yes"></p> <p id="no"></p> <script> const clickme = document.querySelector('#clickme') const yes = document.querySelector('#yes') const no = document.querySelector('#no') let yesScore = 0; let noScore = 0; function game() { clickme.addEventListener('click', myFunction); function myFunction(){ let promptVar = prompt('y/n'); if(promptVar === 'y') yes.textContent = ++yesScore; else if(promptVar === 'n') no.textContent = ++noScore; else return; if(yesScore + noScore === 5){ console.log('over'); clickme.removeEventListener("click",myFunction); } } } </script> </body> 在这里,您不需要退出任何函数,因为单击事件被破坏,如果您单击“单击我”,它不会引发该事件。 请注意,当您退出 myFunction 时,它不会转到 game() 函数,因为它是一个事件。因为每当您单击按钮时都会调用该函数。 希望它对您有用。 您可以在 myFunction 之后在游戏函数内暂停。 这将暂停该线程,并且之后不会再运行任何内容。如果你确实想让 game() 在该条件之后结束,请创建 Promise,除了 console.log、Promise.resolve 之外还注册 myFunction,然后在 myFunction 和 myFunction 上注册,使用 wait 关键字等待该 Promise 解析,然后按照你的意愿行事,但 game() 尚未结束。可能有一个类似等待异步的东西,可以让代码在等待完成之前运行。另外,我建议在 addEventListener 之前使用 myFunction。 === 完全等于,我建议使用 ==。您还可以使用结束函数而不是以 game() 结束。您可以删除事件侦听器内的事件侦听器。就像 someView.removeEventListener(this);. 我发现尝试通过进入 game() 来结束是很困难的,并且有更好的选择。 game() 的所有函数都会立即返回,因此如果您想以 game() 结束,请尝试初始游戏(initial=true),然后使用时间 setTimeout 或 setInterval 以及使用初始 = false 调用游戏的函数,如 game(false) 和 if初始,设置事件侦听器,检查结束条件,然后如果不是结束条件,则 setTimeout 或继续间隔,但如果结束条件没有新的超时,则使用传递给它的函数清除Interval,其中之一或其他。 如果有结束条件,则执行您想要结束的操作。 setTimeout 和 setInterval 允许它们之后的代码在结束之前运行。像这样: function inter() {game(false)} function game(initial=true) { if (initial) { //Starting code } if (end condition) { //End } else { setTimeout(inter, 1000); } } XE.

回答 2 投票 0

在 addEventListener 上调用函数时获取按钮文本的值

所以,我正在为奥丁项目制作这个蚀刻草图,但是,我不知道如何在选择新的画布尺寸时重新绘制画布。 基本上,当点击任何一个屁股时......

回答 1 投票 0

我的代码有什么问题吗?有人可以帮忙吗?它说“无法加载资源:服务器响应状态为 404(未找到)

无法加载资源:服务器响应状态为404(未找到) 我尝试添加事件侦听器以使 pomodro 计时器正常工作。我希望它能在鹅卵石底中给我结果,但它......

回答 0 投票 0

“cypress”(未捕获的异常)类型错误:无法读取 null 的属性(读取“addEventListener”)

在此输入图像描述 在此输入图像描述 在此输入图像描述 你好,我是cypress的新手,首先css选择器是对的,其次你可以清楚地看到“cy”后面的内容。

回答 2 投票 0

addEventListener 不能与 react-router-dom 一起工作

因为 metro-ui-css 不支持表中按钮的 onClick (https://github.com/olton/Metro-UI-CSS/issues/1618) 我不得不在我的组件中使用 addEventLisener。 为了实现我正在关注

回答 0 投票 0

是否可以在“输入”的 evnentListener 中使用 $.ajax

-这是我的javascript: 让 uname = document.getElementsByClassName('登录用户名')\[0\]; let pass = document.getElementsByClassName('登录密码')\[0\]; uname.addEventListener('input', func...

回答 1 投票 0

如何相互独立地引用和使用多个div

我在这里的第一篇文章所以我会尽力而为, 我正在尝试制作一个日历/复选框,我可以在其中跟踪事物的一致性,图片在这里供参考 -->> 在此处输入图片描述。 所有的盒子...

回答 0 投票 0

JS中任何孩子专注时触发事件

考虑以下 HTML: 这个 考虑以下 HTML: <div id="parent"> <div class="line"> <span class ="word">This </span> <span class ="word">is </span> <span class ="word">a </span> <span class ="word">line. </span> </div> <div class="line"> <span class ="word">This </span> <span class ="word">is </span> <span class ="word">another </span> <span class ="word">line. </span> </div> </div> <textarea id="textarea"></textarea> 父级的内容是动态的(它可能会在运行时发生变化)。 我想报告文本区域的父母或任何后代的焦点。例如,如果用户单击父级,焦点将设置在文本区域上。 我做了以下,但它不起作用: let parent = document.getElementById("parent"); let textarea = document.getElementById("textarea"); parent.addEventListner("focus", () => { console.log ("focus"); textarea.focus(); }) 欢迎任何想法。这是一个 JSFiddle:https://jsfiddle.net/Imabot/6y4d931b/ 使父 DIV 可聚焦: <div id="parent" tabindex="-1"> 使用 tabindex="-1" 仅用于点击,如果您想在使用键盘导航时获取事件,则使用 tabindex="0"。 另外,请在此处使用嵌入式代码片段,这样您就可以正确使用它们,例如没有拼写错误。 let parent = document.getElementById("parent"); let textarea = document.getElementById("textarea"); parent.addEventListener("focus", () => { // you have a type here, should be addEventListener console.log ("focus"); textarea.focus(); }); <div id="parent" tabindex="-1"> <div class="line"> <span class ="word">This </span> <span class ="word">is </span> <span class ="word">a </span> <span class ="word">line. </span> </div> <div class="line"> <span class ="word">This </span> <span class ="word">is </span> <span class ="word">another </span> <span class ="word">line. </span> </div> </div> <textarea id="textarea"></textarea>

回答 1 投票 0

我试图在单击文档中的任何位置时在控制台上调用 MauseEvent 的路径属性

帮助。单击文档中的任何位置时,我试图在控制台上调用 mouseEvent 的路径属性,但在我的控制台上输出“pointerEvent”,并且当我调用路径时

回答 0 投票 0

Web3 事件监听器。检查元掩码登录

所以我有这个默认的 metamask 事件侦听器,用于检查用户是否已连接。我添加了一个额外的功能(第 4 行),它将在容器中显示钱包地址。但是,如果我尝试...

回答 1 投票 0

添加事件监听器是不是很奇怪?

<section class="game--section"> <div class="game-space"> <div class="box box1 active-box"></div> <div class="box box2"></div> <div class="box box3"></div> <div class="box box4"></div> <div class="box box5"></div> <div class="box box6"></div> </div> <div class="restart-button">🔁</div> </section> 我有一个包含 6 个子框的 div(.game-space),其中一个是具有绿色背景的 ('.active-Box) 类的活动框, 所以当我点击活动框时,它会将其类(.active-Box)移动到下一个以这种方式提供绿色背景的框,它一直到最后一个框。 我还有重启按钮,当我点击它时,游戏应该重新启动,就像活动框类被标记到第一个框,然后从这里它再次转移到下一个类并一直到结束框点击 但是,在单击重新启动按钮之前,框之间的移动是一个接一个地线性移动,但是在单击重新启动按钮之后,框被跳过而不是线性移动,跳过一些框之间, 为什么 ?任何解决方案? 'use strict' const allBox = document.querySelectorAll('.box'); const activeBox = document.querySelector('.active-box') const restartButton = document.querySelector('.restart-button') let active_box_index = activeBox_index_function(); slideBox(allBox[active_box_index]); function slideBox(pass_active_box) { pass_active_box.addEventListener('click', function() { allBox[active_box_index].classList.remove('active-box') allBox[active_box_index + 1].classList.add('active-box') active_box_index = activeBox_index_function() slideBox(allBox[active_box_index]); }) } console.log(allBox); // active box index function activeBox_index_function() { let index; allBox.forEach((el, indx) => { if (el.matches('.active-box')) { index = indx }; }) return index; } // when restart button clicked restartButton.addEventListener('click', function() { allBox[active_box_index].classList.remove('active-box') allBox[0].classList.add('active-box') active_box_index = activeBox_index_function() }) @import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,200;0,300;0,400;0,600;0,700;0,800;0,900;1,800&display=swap'); @import url('https://fonts.cdnfonts.com/css/common-pixel'); * { padding: 0; margin: 0; box-sizing: border-box; } html { font-size: 62.5%; font-family: 'Poppins', sans-serif; color: black; } .game--section { height: 100vh; background-color: #252525; display: flex; justify-content: center; align-items: center; } .game-space { width: 80rem; height: 10rem; padding: 1rem; border-radius: 9px; background-color: #f5f5f5; display: grid; grid-template-columns: repeat(6, 1fr); gap: 1rem; } .box { background-color: tomato; } .active-box { background-color: #099268; cursor: pointer; } .restart-button { font-size: 3rem; cursor: pointer; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <section class="game--section"> <div class="game-space"> <div class="box box1 active-box"></div> <div class="box box2"></div> <div class="box box3"></div> <div class="box box4"></div> <div class="box box5"></div> <div class="box box6"></div> </div> <div class="restart-button">🔁</div> </section> <script src="script.js"></script> </body> </html> 你描述的问题是因为事件监听器的积累。 您可以使用以下代码: 'use strict' const allBox = document.querySelectorAll('.box'); const activeBox = document.querySelector('.active-box') const restartButton = document.querySelector('.restart-button') let active_box_index = activeBox_index_function(); slideBox(allBox[active_box_index]); function myFunction(){ allBox[active_box_index].classList.remove('active-box'); if (!((active_box_index + 1)===allBox.length)){ allBox[active_box_index + 1].classList.add('active-box'); } allBox[active_box_index].removeEventListener('click', myFunction); active_box_index = activeBox_index_function(); slideBox(allBox[active_box_index]); } function slideBox(pass_active_box) { if (!((active_box_index + 1)===allBox.length)){ pass_active_box.addEventListener('click', myFunction) } } console.log(allBox); // active box index function activeBox_index_function() { let index; allBox.forEach((el, indx) => { if (el.matches('.active-box')) { index = indx }; }) return index; } // when restart button clicked restartButton.addEventListener('click', function() { allBox[active_box_index].classList.remove('active-box'); allBox[0].classList.add('active-box'); allBox[active_box_index].removeEventListener('click', myFunction); allBox[0].addEventListener('click', myFunction); active_box_index = activeBox_index_function() }) 变化是: 添加removeEventListener() 和其他几个错误修复: 仅当不是最后一个框时才传递类并添加事件监听器。如果需要,您可以将第一个框设置为最后一个框之后的活动框。只需添加一个else语句并在其中添加allBox[0].classList.add('active-box');。 同样不要忘记添加事件监听器.... 希望你觉得这有用! 编辑:我刚刚发现,如果我们定义函数,我们不必添加removeEventListener()。这是因为如果该函数已经在该目标的事件侦听器列表中,则不会再次添加该函数。但是当我们用匿名函数调用事件监听器时,它是第二次添加的。请参阅this answer和MDN Web Docs about addEventListener().

回答 1 投票 0

EventListener 的匿名函数和传递给 EventListener 的定义函数是否工作不同?

我有一个包含 6 个子框的 div(.game-space),其中一个是具有绿色背景的 ('.active-Box) 类的活动框, 所以当我点击活动框时,它会将它的类(.active-Box)转移到...

回答 2 投票 0

AddeventListener 表现怪异?

<section class="game--section"> <div class="game-space"> <div class="box box1 active-box"></div> <div class="box box2"></div> <div class="box box3"></div> <div class="box box4"></div> <div class="box box5"></div> <div class="box box6"></div> </div> <div class="restart-button">🔁</div> </section> 我有一个包含 6 个子框的 div(.game-space),其中一个是具有绿色背景的 ('.active-Box) 类的活动框, 所以当我点击活动框时,它会将其类(.active-Box)移动到下一个以这种方式提供绿色背景的框,它一直到最后一个框。 我还有重启按钮,当我点击它时,游戏应该重新启动,就像活动框类被标记到第一个框,然后从这里它再次转移到下一个类并一直到结束框点击 但是,在单击重新启动按钮之前,框之间的移动是一个接一个地线性移动,但是在单击重新启动按钮之后,框被跳过而不是线性移动,跳过一些框之间, 为什么 ?任何解决方案? 'use strict' const allBox = document.querySelectorAll('.box'); const activeBox = document.querySelector('.active-box') const restartButton = document.querySelector('.restart-button') let active_box_index = activeBox_index_function(); slideBox(allBox[active_box_index]); function slideBox(pass_active_box) { pass_active_box.addEventListener('click', function() { allBox[active_box_index].classList.remove('active-box') allBox[active_box_index + 1].classList.add('active-box') active_box_index = activeBox_index_function() slideBox(allBox[active_box_index]); }) } console.log(allBox); // active box index function activeBox_index_function() { let index; allBox.forEach((el, indx) => { if (el.matches('.active-box')) { index = indx }; }) return index; } // when restart button clicked restartButton.addEventListener('click', function() { allBox[active_box_index].classList.remove('active-box') allBox[0].classList.add('active-box') active_box_index = activeBox_index_function() }) @import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,200;0,300;0,400;0,600;0,700;0,800;0,900;1,800&display=swap'); @import url('https://fonts.cdnfonts.com/css/common-pixel'); * { padding: 0; margin: 0; box-sizing: border-box; } html { font-size: 62.5%; font-family: 'Poppins', sans-serif; color: black; } .game--section { height: 100vh; background-color: #252525; display: flex; justify-content: center; align-items: center; } .game-space { width: 80rem; height: 10rem; padding: 1rem; border-radius: 9px; background-color: #f5f5f5; display: grid; grid-template-columns: repeat(6, 1fr); gap: 1rem; } .box { background-color: tomato; } .active-box { background-color: #099268; cursor: pointer; } .restart-button { font-size: 3rem; cursor: pointer; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <section class="game--section"> <div class="game-space"> <div class="box box1 active-box"></div> <div class="box box2"></div> <div class="box box3"></div> <div class="box box4"></div> <div class="box box5"></div> <div class="box box6"></div> </div> <div class="restart-button">🔁</div> </section> <script src="script.js"></script> </body> </html> 您可以按以下方式更新您的代码: 删除对 slideBox 的递归调用并增加 active_box_index 变量。 检查 active_box_index 是否已到达框的末尾,如果是则将其重置为 0. 在 restartButton event 侦听器中将 active_box_index 变量重置为 0 而不是 calling activeBox_index_function(). 'use strict' const allBox = document.querySelectorAll('.box'); const activeBox = document.querySelector('.active-box') const restartButton = document.querySelector('.restart-button') let active_box_index = activeBox_index_function(); slideBox(allBox[active_box_index]); function slideBox(pass_active_box) { pass_active_box.addEventListener('click', function() { allBox[active_box_index].classList.remove('active-box'); active_box_index++; //increment the index instead of using activeBox_index_function() to calculate it again if (active_box_index === allBox.length) { //if reached the end of the boxes, reset the index to 0 active_box_index = 0; } allBox[active_box_index].classList.add('active-box'); }) } //console.log(allBox); // active box index function activeBox_index_function() { let index; allBox.forEach((el, indx) => { if (el.matches('.active-box')) { index = indx }; }) return index; } // when restart button clicked restartButton.addEventListener('click', function() { allBox[active_box_index].classList.remove('active-box') allBox[0].classList.add('active-box') active_box_index = 0; //reset the index to 0 when restarting the game }) @import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,200;0,300;0,400;0,600;0,700;0,800;0,900;1,800&display=swap'); @import url('https://fonts.cdnfonts.com/css/common-pixel'); * { padding: 0; margin: 0; box-sizing: border-box; } html { font-size: 62.5%; font-family: 'Poppins', sans-serif; color: black; } .game--section { height: 100vh; background-color: #252525; display: flex; justify-content: center; align-items: center; } .game-space { width: 80rem; height: 10rem; padding: 1rem; border-radius: 9px; background-color: #f5f5f5; display: grid; grid-template-columns: repeat(6, 1fr); gap: 1rem; } .box { background-color: tomato; } .active-box { background-color: #099268; cursor: pointer; } .restart-button { font-size: 3rem; cursor: pointer; } <section class="game--section"> <div class="game-space"> <div class="box box1 active-box"></div> <div class="box box2"></div> <div class="box box3"></div> <div class="box box4"></div> <div class="box box5"></div> <div class="box box6"></div> </div> <div class="restart-button">🔁</div> </section>

回答 1 投票 0

事件侦听器已附加但无法在 React js 中工作

我有一个 React 项目,其中有一个“高度:100vh 溢出:隐藏”的父项,其 id:parent_div。在该父级中,称为 ContentSection 的子组件具有高度:100vh overflo ...

回答 1 投票 0

如何从复选框列表中选择所有复选框(例如:待办事项列表)

我正在尝试创建一个待办事项列表,每个项目都有一个复选框,我想在单击它们时选中这些复选框中的每一个。如果我再次点击它们中的任何一个,该框应该在选中之间切换...

回答 2 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.