Javascript 如何将自定义数据发送到JQuery单击事件?

Javascript 如何将自定义数据发送到JQuery单击事件?,javascript,jquery,onclick,jquery-events,Javascript,Jquery,Onclick,Jquery Events,我有一个JQuery单击事件: jq("#generateButton").click({key: "hello world"}, function () { console.dir(this);// this is the "generateButton" html element. // jq(this) would be the jquery object of the generate button frnConstr.s

我有一个JQuery单击事件:

jq("#generateButton").click({key: "hello world"}, function () {
            console.dir(this);// this is the "generateButton" html element. 
        // jq(this) would be the jquery object of the generate button
            frnConstr.setDataObject(this);
        frnConstr.gameObject.state.start(frnConstr.EnteriorScreen.KEY);
    });
我如何可能将自定义数据发送到此事件,例如打印{key:“hello world”}? 有可能吗

注意:在我定制的工作环境中,jq()是$()或jquery()

注意:jQuery文档说eventData可以是任何东西,下面是官方文档:
:)

您不能,但一种解决方法是在html中有一个数据属性,并在单击该元素时获取该属性

例如:


jq(“生成按钮”)。单击(函数(){
console.log($(this.data('key'));//什么
.....
});

通常情况下,您会为此使用数据属性,并使用

jq("#generateButton").on("click",function() {
  var custom = $(this).data("custom");
});
使用

<button id="generateButton" data-custom="hello world"> 

你好,世界
再见世界

序列化:

单击以序列化
首先,确保您参考的是jquery 1.4.3版或更高版本

jq("#generateButton").click({key: "hello world"}, function (event) {
    var key=event.data.key;
    //do something with the key value
});

此eventData签名中传递的所有数据都可以在event.data对象中访问。

除了版本之外,我的回答中还没有提到什么?Event.data是在1.1 btwYes中添加的,我有最新的JQuery版本。它只是一个执行函数的generate按钮。如果“this”对象是generateButton本身,那么如何将用JQuery序列化的表单数据数组发送到click事件?访问家长?:)当然:$(this).closest(“form”).serialize()@Vlad我仍然对您选择接受的答案感到惊讶。它比我的晚了15分钟,没有运行的示例,似乎没有回答您真正想知道的问题-这似乎在同一时间发生了变化:)Moar points please:P我一直在忙于调试我的代码。我唯一能利用的就是$(this).nexist(“form”).serialize(),它不在您的答案中。是的,我不会用generate按钮绑定数据结构。它应该只运行一个函数。但别担心,我相信很多人会发现你的答案很有用,我自己也一样。最重要的答案要干净得多。发送事件数据,以及处理程序中的事件对象。
jq("#generateButton").on("click",{"what":"hello"}, function(event) {
  var custom = $(this).data("custom");
  console.log(event.data.what+" "+custom); // hello world
});

<button id="generateButton" data-custom="world"> 
jq("#generateButton").click({key: "hello world"}, function (event) {
    var key=event.data.key;
    //do something with the key value
});