从Javascript中的元素列表中检查导致事件的元素

时间:2014-06-02 17:11:30

标签: javascript html5 addeventlistener

我有一个包含其事件监听器的元素列表:

var h1 = document.getElementById("h1"),
    h2 = document.getElementById("h2"),
    h3 = document.getElementById("h3");

var elemArray = [h1,h2,h3];

for(var i=0;i<elemArray.length;i++){
    elemArray[i].addEventListener("click",mouseListener,false);
}

function mouseListener(e){
    // code goes here
    // whenever it's called i want to know from
    // which element it's been called
}

现在我想要的是每当我点击其中一个元素时, 我想知道哪一个被点击而没有为每个元素使用不同的函数。

3 个答案:

答案 0 :(得分:3)

只需在回调中使用this变量,它就会指向目标元素:

function mouseListener(e) {
    console.log( this.id );
}

答案 1 :(得分:0)

function mouseListener(e){
     var elementEventWasSet = this;
     var clickedEl = e.target; // in case of bubbling, this is the one that was clicked
    // code goes here
    // whenever it's called i want to know from
    // which element it's been called
}

答案 2 :(得分:0)

你可以做这样的事情

function mouseListener(e){
    if(this === h1){
        console.log("First was pressed");
    }else if(this === h2){
        console.log("Second was pressed");
    }else if(this === h3){
        console.log("Third was pressed");
    }
}

仅当h1,h2和h3是全局变量时才会起作用。 您可以在此网站上看到此方法: http://jsfiddle.net/94xMu/2/