for循环内的JS DOM无法使用字符串

时间:2018-12-18 16:11:55

标签: javascript dom

这是HTML:

<ul class="drum">
 <li>A</li>
 <li>S</li>
 <li>D</li>
</ul>

这是JS:

const Olist = document.querySelectorAll('.drum li');
  for(let i = 0; i < Olist.length; i++){
    Olist[i].addEventListener('click', function(e){
        console.log(`I was clicked ${Olist[i]}`);
    })
 }

循环中的console.log()返回以下内容:I was clicked [object HTMLLIElement]我不明白为什么得到[HTMLLIElement]而不是实际的li

编辑 我试图了解为什么我得到的结果与单纯console.log(Olist[i])时的结果不同。过去我已经做过很多次,但是我认为这里缺少一些基本的东西。

2 个答案:

答案 0 :(得分:2)

您之所以得到该值,是因为I was clicked ${Olist[i]}.toString()实例上调用HTMLLIElement。如果要查看元素的HTML,请尝试调用I was clicked ${Olist[i].outerHTML}

const Olist = document.querySelectorAll('.drum li');


for (let i = 0; i < Olist.length; i++) {
  Olist[i].addEventListener('click', function(e) {
    console.log(`I was clicked ${Olist[i].outerHTML}`);
    console.log(`Olist[i].toString() => ${Olist[i].toString()}`);
  })
}
<ul class="drum">
  <li>A</li>
  <li>S</li>
  <li>D</li>
</ul>

答案 1 :(得分:0)

这是一个简单的解决方案。

// Convert a HTMLCollection to an array, then apply the following code for each item
// within the array.
Array.prototype.slice.call(document.querySelectorAll('.drum li')).map(li => li.onclick = () => {
  const string = li.outerHTML;
  console.log(string + ' Was clicked');
});
<ul class="drum">
 <li>A</li>
 <li>S</li>
 <li>D</li>
</ul>