如何在JavaScript中添加参数到onclick事件?

3

基本上,当按钮被按下时,我想要提供一个参数,但这并不起作用:

var button = document.getElementById("button");
button.onClick = doThis(arg);

但是这个方法可以工作(不带参数):
var button = document.getElementById("button");
button.onClick = doThis;

第一个例子不起作用的原因是函数会自动运行而不等待点击事件发生。
如何在onClick事件中传递参数?
3个回答

5
首先,请注意它是onclick,而不是onClick。两者都可以在主要浏览器上使用,但前者是正确的大小写。(请参见HTML规范中的此处此处,包括代码示例。)
您有几个选择:
  1. Use Function#bind:

    button.onclick = doThis.bind(button, arg);
    

    Function#bind creates a new function that, when called, will call the original with a specific this value (the first argument, button in our case) and any arguments you give it (followed by any arguments the new function is called with).

  2. Use a wraper function:

    button.onclick = function() { doThis(arg); };
    

    within the above, though, this in doThis will not be the button. If you want it to be, you can use Function#call:

    button.onclick = function() { doThis.call(button, arg); };
    // or
    button.onclick = function() { doThis.call(this, arg); };
    

    Function#call calls a function, specifying the this value to use, along with the arguments to pass to it.


1

您可以使用匿名函数来完成此操作。

document.getElementById("button").onClick = function() { doThis(arg); };

这正是我一直在寻找的,尽管它看起来有点奇怪。谢谢! - mre12345
不清楚。但是针对@OP,我一定会接受T.J的答案,因为它比我的更全面。 - CollinD

0
你可以使用JavaScript中的addEventListener来很好地完成它。 HTML5数据属性和DOMStringMap可用于进一步扩展它。
下面的代码片段应该为您提供使用任何HTMLDomEvents的参数的公平想法。
el.addEventListener('click', function(e) {
  performAction(e, this);
});

var elContainer = document.querySelector('#myDiv');
var el = document.querySelector('#searchNow');

el.addEventListener('click', function(e) {
  performAction(e, this);
});

function performAction(e, thatObj) {
  var str = '' + e.type + '\n';
  for (x in thatObj.dataset) {
    str += x + ': ' + thatObj.dataset[x] + '\n';
  }

  console.log(e.type + thatObj.dataset);
  elContainer.innerHTML += str;

}
#myDiv {
  margin: 5px 0;
  padding: 5px;
  border: 1px solid #CCC;
}
<div id="myDiv">
  My DIV...
  <br/>
</div>

<button name='search' id='searchNow' data-propertiesObject='{a: "XYZ", b: "ABC"}'>Search Now!</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接