【问题标题】:How can I pass a custom argument to an event listener in JavaScript?如何将自定义参数传递给 JavaScript 中的事件侦听器?
【发布时间】:2010-12-24 18:17:17
【问题描述】:

如何添加一个也接受参数的事件监听器(addEventListener(),attachEvent())?

参数作为元素的自定义属性传递,如:

<img src="icon.gif" alt="Test button" command="test" />
<img src="icon2.gif" alt="Test button2" command="write" />

【问题讨论】:

    标签: javascript event-handling


    【解决方案1】:

    您可以在处理程序中使用 getAttribute,例如

    var param = this.getAttribute('command');

    【讨论】:

      【解决方案2】:

      你可以这样使用:

      element.addEventListener ( 'click', (function ( myParam ) {
          return function () {
              // user myParam here
          };
      } ) ( yourParam ), false );
      

      无论您以“yourParam”的形式传入什么,事件处理程序都可以通过“myParam”参数访问...

      【讨论】:

      • 这对我有用:attachEvent('onclick', function() { linkClicked(link.getAttribute("command")); }, false);
      猜你喜欢
      • 1970-01-01
      • 2011-09-18
      • 2015-12-07
      • 1970-01-01
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      相关资源
      最近更新 更多