Event handler scope in Javascript

后端 未结 3 1384
臣服心动
臣服心动 2021-01-14 10:03

This is probably an easy question but I can\'t figure out the best answer for it.

I have 10

elements on screen. Each of them has a cli
3条回答
  •  醉话见心
    2021-01-14 10:13

    You could grab the number from the element's id attribute:

    for ( var i = 0; i < 10; i++ ) {
        var element = document.getElementById( "element" + i );
        element.onclick = function () {
    
            var i = this.id.substr(7);
            alert( "Element " + i );
        }
    }​
    

    JsFiddle here.

提交回复
热议问题