我正在尝试创建一个非常简单的表单。我的目标是创建两个可点击的按钮,每个按钮包含一个问题。单击时,DOM将在每个按钮下方输出答案。棘手的部分是让两个按钮只响应一个" addEventListener"。这是我的代码:
HTML:
<div id="wrapper">
<header>
<h1>Have you ever wondered...</h1>
</header>
<div>
<button id="myBtn">How many licks it takes to get to the center of a tootsie pop?</button>
<p id="first"></p>
<h3>Or what about...</h3>
<button id="myBtnTwo">How tall the Eiffel Tower is?</button>
<p id="second"></p>
</div>
</div>
JS:
document.getElementById("myBtn").addEventListener("click", function(){
document.getElementById("first").innerHTML= "Approximately 364 licks!";
});
document.getElementById("myBtnTwo").addEventListener("click", function(){
document.getElementById("second").innerHTML= "984 feet!";
});
提前谢谢!
答案 0 :(得分:0)
您只能将一个元素绑定到JS中的每个事件侦听器。但是,您可以将多个不同的事件与一个元素关联。
现在,要解决您的问题:解决此问题的一种方法是将事件处理程序附加到父元素,然后找到作为事件目标的元素。
<div id="wrapper">
<header>
<h1>Have you ever wondered...</h1>
</header>
<div id="btn-wrapper">
<button id="myBtn">How many licks it takes to get to the center of a tootsie pop?</button>
<p id="first"></p>
<h3>Or what about...</h3>
<button id="myBtnTwo">How tall the Eiffel Tower is?</button>
<p id="second"></p>
</div>
如您所见,我将ID btn-wrapper
添加到父div。然后在JS中,我将处理程序附加到所述父元素。然后,您可以找到事件目标并根据它来运行您的代码。
var theParent = document.querySelector("#btn-wrapper");
theParent.addEventListener("click", doSomething, false);
function doSomething(e) {
if (e.target !== e.currentTarget) {
if (e.target === document.querySelector('#myBtn')) {
document.querySelector("#first").innerHTML= "Approximately 364 licks!";
} else if (e.target === document.querySelector('#myBtnTwo')) {
document.querySelector("#second").innerHTML= "984 feet!";
}
}
e.stopPropagation();
}
要阅读有关该主题的更多信息:https://www.kirupa.com/html5/handling_events_for_many_elements.htm