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?

最佳答案

最快,最简单的方法:

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

10-06 04:06