<button test="page1">page1</button>
<button test="page2">page2</button>
<br>
<button test2="page1">page1</button>
<button test2="page2">page2</button>
var location = document.querySelectorAll("[test]");
var location2 = document.querySelectorAll("[test2]");
location.forEach(function(e1, e2){
location[e2].addEventListener("click", function(){
alert(location[e2].getAttribute("test"));
});
});
for(var i = 0; i < location2.length; i++){
location2[i].addEventListener("click", function(){
alert(location2[i].getAttribute("test2"));
});
}
https://jsfiddle.net/zeus1309/jqL8b0rt/
foreach的版本有效。但是那个没有。 我不明白为什么。
答案 0 :(得分:0)
而不是location2[i].getAttribute("test2")
使用this.getAttribute("test2")
。
注意:在forEach()
函数中,您不必同时使用这两个参数。
var location = document.querySelectorAll("[test]");
var location2 = document.querySelectorAll("[test2]");
location.forEach(function(e){
e.addEventListener("click", function(){
alert(e.getAttribute("test"));
});
});
for(var i = 0; i < location2.length; i++){
location2[i].addEventListener("click", function(){
alert(this.getAttribute("test2"));
});
}
<button test="page1">page1</button>
<button test="page2">page2</button>
<br>
<button test2="page1">page1</button>
<button test2="page2">page2</button>