How To call the same Method for different Elements with different IDs?
Lets say i have 3 p-Elements. If i click on one of them its Text should change. But how can i do it without writing a Method for every Element?
<!DOCTYPE html>
<html>
<body>
<p>This example uses the HTML DOM to assign an "onclick" event to a p element.</p>
<p id="demo">Click me.</p>
<p id="demo2">Click me.</p>
<script>
document.getElementById("demo").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}
</script>
</body>
</html>
In this example if i click on the first one it works. But not for the second one. And i dont want to write the same method over and over and just change the Ids. There must be a more simple way. Any ideas?
如果你需要多元素的同一个监听器,我会建议使用class而不是id
var p = document.querySelectorAll(".selector");
p.forEach(function(el) {
el.addEventListener('click', myEventHandler);
})
function myEventHandler(event) {
event.target.innerHTML = "YOU CLICKED ME!";
}
<p>This example uses the HTML DOM to assign an "onclick" event to a p element.</p>
<p class="selector">Click me.</p>
<p class="selector">Click me.</p>
First of all, elements shouldn't have the same id.
Second, have your function accept a parameter for the event. This will let you get the thing that you clicked on.
Third you just want to set some text so switch out innerHTML
for textContent
.
<p id="demo">Click me.</p>
<p id="demo2">Click me.</p>
<script>
document.getElementById("demo").onclick = myFunction;
document.getElementById("demo2").onclick = myFunction;
function myFunction(e) {
e.target.textContent = "YOU CLICKED ME!";
}
</script>
Add a class in all of them and use document.querySelectorAll(".p");
to add event listeners for all of them
var o = document.querySelectorAll(".p");
for(var i=0; i<o.length; i++){
o[i].addEventListener("click", function(e){
e.target.innerHTML = "You clicked ME"
})
}
<!DOCTYPE html>
<html>
<body>
<p>This example uses the HTML DOM to assign an "onclick" event to a p element.</p>
<p id="demo" class="p">Click me.</p>
<p id="demo2" class="p">Click me.</p>
</body>
</html>
链接地址: http://www.djcxy.com/p/83466.html