将param传递给匿名函数

时间:2015-08-20 18:57:07

标签: javascript

我试图将参数传递给匿名函数。但有些事情是错的,我无法理解。



function getInfo(item) {
  alert(item); //does not pass the item?
}
var param = "Param was passed successfully!";
var elementel = document.getElementById("AlretBtn");
elementel.addEventListener("click", getInfo.bind(null, param, false);

<button id="AlretBtn">Alert Item</button>
&#13;
&#13;
&#13;

这有什么问题?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

&#13;
&#13;
function getInfo(item) {
  alert(item); //does not pass the item?
}
var param = "Param was passed successfully!";
var elementel = document.getElementById("AlretBtn");
elementel.addEventListener("click", getInfo.bind(null, param, false));
&#13;
<button id="AlretBtn">Alert Item</button>
&#13;
&#13;
&#13;

您缺少一个括号。我不知道您使用的是IDE,还是您的开发环境。但是,尝试添加一个javascript语法验证器,它确实使开发更快:)

答案 1 :(得分:2)

我不确定你打算做什么,但是你没有把任何东西绑定到getInfo()。如果您想将click处理程序绑定到button元素:

function getInfo(item){
    alert(item); //does not pass the item?
    console.log(this); // the button element instead of Window
}
var param = "Param was passed successfully!";
var elementel = document.getElementById("AlretBtn");
elementel.addEventListener("click", getInfo.bind(elementel, param, false));

如果您不需要将点击处理程序绑定到它,为什么还要使用bind()?:

function getInfo(item){
    alert(item); //does not pass the item?
}
var param = "Param was passed successfully!";
var elementel = document.getElementById("AlretBtn");
elementel.addEventListener("click", function(){ getInfo(param); });

without bind()