如何创建对匿名addEventListener处理程序的引用?

时间:2013-05-20 05:13:23

标签: javascript event-handling addeventlistener

function alertString(str) {
    alert(str);
}

var str = "hello";
var alert_string = document.getElementById("alert_str");

// this can be removed with removeEventListener
// alert_str.addEventListener("click", alertString, false);

// but since I need to pass an argument
// alertString is wrapped within an anonymouse function
alert_string.addEventListener("click", function() {
    alertString(str);
}, false);

document.getElementById("remove_alert").onclick = function() {
    alert_string.removeEventListener("click", alertString, false);
};
<input type="button" id="alert_str" value="alert" />
<input type="button" id="remove_alert" value="remove alert" />

无法删除click事件处理程序,因为它包含在anonymouse函数中。

如何创建对该函数的引用,以便从警报按钮中删除alertString?

1 个答案:

答案 0 :(得分:2)

最快,最简单的方法:

function alertStringWrapper() {
    alertString(str);
}
alert_string.addEventListener("click", alertStringWrapper, false);