繁体   English   中英

将参数传递给事件处理程序函数的最佳实践

[英]Best practice for passing arguments to an event handler function

假设我有一个按钮(实际上是几个按钮),单击该按钮将执行2件事中的1件事。 这2件事中的哪一个取决于传递给函数的参数。 这将被全部使用,因此我需要放置一个函数...而不是每次都在匿名函数中执行代码。 我正在使用jquery,想知道什么是向click-handler函数提供参数和值的最佳方法。 另外,如果可能的话,我想完整地保留对按钮的引用为$(this) 这是我所拥有的:

$(document).ready(function() {
   $('#button1').click({ labelStr: 'Open File' }, doLabel);
   $('#button2').click({ labelStr: 'Close Window' }, doLabel);
});

function doLabel(e) {
  console.log('it is: %o', e.data.labelStr);
  $(this).html(e.data.labelStr);
}

...有效-jsfiddel-但我知道有很多方法可以给这只猫皮。 这种方法可以戳出什么洞?

您的代码对我来说很好。 您是否正在寻找传递参数并将其直接映射到点击处理程序的参数列表的方法? 如果是这样,您可以尝试以下方法:

$(document).ready(function() {
   $('#button1').click(function() {doLabel.call(this, "Open File");});
   $('#button2').click(function() {doLabel.call(this, "Close Window");});
});

function doLabel(labelStr) {
  console.log('it is: %o', labelStr);
  $(this).html(labelStr);
}

如果有多个参数,则可以执行doLabel.call(this, arg1, arg2, ...)

就像DelightedD0D建议的一样,我也将使用数据属性。 您可以在事件处理程序中使用$(this)来引用元素,因此避免使用匿名函数。

 $(document).ready(function() { $('button').click(doLabel); }); function doLabel() { $(this).html($(this).data('label-str')); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <button data-label-str="Open File">Give me a label please</button> <p>&nbsp;</p> <button data-label-str="Close Window">Give ME a label TOO please</button> 

如果我理解正确的话,我只是添加字符串作为按钮的数据属性和发送this给函数。 让函数使用this从按钮获取字符串

的jsfiddle

 $(document).ready(function() { $('button').click(function(){doLabel(this)}); }); function doLabel(e) { $(e).html($(e).data('label-str')); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <button data-label-str="Open File">Give me a label please</button> <p>&nbsp;</p> <button data-label-str="Close Window">Give ME a label TOO please</button> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM