0
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 事件处理程序不能被删除,因为它被包装在一个匿名函数中。

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

4

1 回答 1

2

最快、最简单的方法:

function alertStringWrapper() {
    alertString(str);
}
alert_string.addEventListener("click", alertStringWrapper, false);
于 2013-05-20T05:17:01.100 回答