最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - For of and click event in es6 - Stack Overflow

programmeradmin5浏览0评论

if I use jquery it's working.

$(document).ready(function() {
   $('btn').click(function() {
       alert('start');
   });
});

but I want use native es6

window.onload = function() {
    let btn = document.getElementsByClassName( 'btn' );
    for (let i of btn.length) {
        i.onclick( function () {
            alert( 'start' );
        });
    }
};

error btn.length[Symbol.iterator] is not a function

And this doesn't work too.

window.onload = function() {
    let btn = document.getElementsByClassName( 'btn' );
    for (let i=0; i < btn.length; i++) {

        i.onclick = function () {
            alert( 'start' );
        };
    }
};

if I use jquery it's working.

$(document).ready(function() {
   $('btn').click(function() {
       alert('start');
   });
});

but I want use native es6

window.onload = function() {
    let btn = document.getElementsByClassName( 'btn' );
    for (let i of btn.length) {
        i.onclick( function () {
            alert( 'start' );
        });
    }
};

error btn.length[Symbol.iterator] is not a function

And this doesn't work too.

window.onload = function() {
    let btn = document.getElementsByClassName( 'btn' );
    for (let i=0; i < btn.length; i++) {

        i.onclick = function () {
            alert( 'start' );
        };
    }
};
Share Improve this question asked Jul 8, 2017 at 22:23 Atm54_17Atm54_17 1793 silver badges8 bronze badges 2
  • 2 Second one should be btn[i].onclick=... not i.onclick .. i is a number not an element – charlietfl Commented Jul 8, 2017 at 22:29
  • 1 for... of iterates a collection - so for(let btn of buttons) { ... and not of buttons.length – Benjamin Gruenbaum Commented Jul 8, 2017 at 22:35
Add a ment  | 

1 Answer 1

Reset to default 6

The for of loop will iterate over the elements of a collection that has a [Symbol.iterator] property. In your ES6 snippet you are trying to iterate over the returned HTMLCollection length eg. for (let i of btn.length)....

Here is what you should do instead.

let btns = document.getElementsByClassName( 'btn' );

for ( let btn of btns ) {
  btn.onclick = function() {
    console.clear()
    console.log(this.textContent)
  }
}
<button class="btn">Btn 1</button>
<button class="btn">Btn 2</button>
<button class="btn">Btn 3</button>
<button class="btn">Btn 4</button>

发布评论

评论列表(0)

  1. 暂无评论