简体   繁体   English

使用自己的参数触发click事件(JavaScript first,alternative JQuery)

[英]Trigger a click event with own parameters (JavaScript first, alternative JQuery)

I'm looking for a way to pass parameters to the event handler (addEventListener) when the click event of eg an button is triggered by code. 我正在寻找一种方法,当代码触发例如按钮的单击事件时,将参数传递给事件处理程序(addEventListener)。 My solution is to add an own attribute to the element itself, like document.getElementById("ButtonId").MyAttribute = MyValue ; 我的解决方案是向元素本身添加一个自己的属性,例如document.getElementById("ButtonId").MyAttribute = MyValue ; document.getElementById("ButtonId").click() ;

But I'm really interested in other solutions which should use first off all only JavaScript and then as an alternative JQuery. 但是我真的对其他解决方案很感兴趣,这些解决方案应首先使用所有JavaScript,然后再作为替代JQuery使用。 I'm aware of the JQuery event.data object, but maybe there are other solutions. 我知道JQuery event.data对象,但也许有其他解决方案。

Many thanks and greetings 非常感谢和问候
ANTLRStarter ANTLRStarter

The data object is the way to go. 数据对象是要走的路。 If you'd rather use pure JavaScript you could simply leverage HTML5's data-* attribute ( http://www.w3schools.com/tags/att_global_data.asp ). 如果你更喜欢使用纯JavaScript,你可以简单地利用HTML5的data- *属性( http://www.w3schools.com/tags/att_global_data.asp )。

You may want to create the javascript function with parameter passing, and use addEventLister with your own parameter(s) 您可能希望使用参数传递创建javascript函数,并将addEventLister与您自己的参数一起使用

// javascript function with parameter passing
function myFunctionA(p1) {
  // code
}

var v1 = document.getElementById("ButtonId");
v1.addEventListener("click", function(){myFunctionA("myParameter")}, false);

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

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