我正在尝试使用函数内的 id 捕获按钮的 onclick
事件,然后尝试 console.log
值!但我认为因为事件捕获代码在函数内部,所以它不会检测事件何时触发!有什么办法解决它!谢谢!
window.onload = xyz;
function xyz() {
click();
}
function click() {
var x = document.querySelector("#btn");
x.addEventListener("click", myfunction);
console.log(x);}
function myfunction() {
document.querySelector(".example").style.backgroundColor = "red";
return 1;
}
<h2 class="example">A heading with class="example"</h2>
<p>Click the button to add a background color to the first element in the document with class="example".</p>
<button id="btn">Try it</button>
最佳答案
您可以将点击函数变成 IIFE:
(function click() {
var x = document.querySelector("#btn");
x.addEventListener("click", myFunction);
console.log(x);
})()
function myFunction() {
document.querySelector(".example").style.backgroundColor = "red";
return 1;
}
<h2 class="example">A heading with class="example"</h2>
<p>Click the button to add a background color to the first element in the document with class="example".</p>
<button id="btn">Try it</button>
调用函数时还要确保大小写匹配
关于javascript - 有什么方法可以使用元素的 id 或类来捕获函数内部的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53415071/