Using this in event handler in strict javascript?

前端 未结 3 1834
别那么骄傲
别那么骄傲 2021-01-25 19:49

Suppose you have a routine like the following to wire up click event handlers

getElements(\".board>div\").forEach(function(elem){
  elem.addEventListener(\"cl         


        
3条回答
  •  滥情空心
    2021-01-25 20:14

    use one eventhandler

    especially if you have many elements inside your board.

    adding multiple eventlisteners slows down the browser.

    js

    function h(e){
     alert(e.target.textContent)
    }
    document.getElementsByClassName('board')[0].onclick=h
    

    or

    document.querySelector('.board').addEventListener('click',h,false)
    

    html

    1
    2
    3
    4

    example

    http://jsfiddle.net/3csJ2/

    in your case...

    function h(e){
     e.target.innerText==1||(alert('this is not 1')/*,...*/) 
    }
    

    example 2

    http://jsfiddle.net/3csJ2/1/

    inside the handler function (h) this is the 'board'.

提交回复
热议问题