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?