如何将字符串结果收集到每个循环内的单个数组
<ul>
<li data-tag="two"></li>
<li data-tag="three"></li>
<li data-tag="four"></li>
<li data-tag="five"></li>
</ul>
<button id="ev">Click</button>
JavaScript的:
var elem = Array.prototype.slice.call(document.querySelectorAll('ul > li'));
document.getElementById('ev').addEventListener('click', function(ev){
elem.forEach( function(el,i) {
var ar = ["one"];
var tags = el.getAttribute('data-tag');
ar.push(tags);
});
});
结果:
["one", "two"]
["one", "three"]
["one", "four"]
["one", "five"]
期待结果:
["one", "two", "three", "four", "five"]
答案 0 :(得分:2)
在arr
forEach
var elem = Array.prototype.slice.call(document.querySelectorAll('ul > li'));
document.getElementById('ev').addEventListener('click', function(ev) {
var ar = ["one"];
elem.forEach( function(el,i) {
var tags = el.getAttribute('data-tag');
ar.push(tags);
});
console.log(ar);
});
<ul>
<li data-tag="two"></li>
<li data-tag="three"></li>
<li data-tag="four"></li>
<li data-tag="five"></li>
</ul>
<button id="ev">Click</button>
答案 1 :(得分:0)
探测器是你在forEach函数中声明ar
变量,它会覆盖值而不是将它们推入数组。
var ar = ['one'];
elem.forEach( function(el,i) {
var tags = el.getAttribute('data-tag');
ar.push(tags);
});
&#13;