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

How can I send custom data to JQuery click event?

我有这个 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 可以是任何东西,这里是官方文档: https://api.jquery.com/click/:)

您只能在 html 中添加一个数据属性,然后在单击该元素时获取该属性。

例如:

 <button id="generateButton" data-key="something"/>

jq("#generateButton").click(function () {
    console.log($(this).data('key')); // something
    .....
});

通常你会为此使用数据属性并用

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

使用

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

您指的是在绑定时发送的 event.data

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"> 

例子

$(function() {
  $("#generateButton1").on("click", function() {
    var custom = $(this).data("custom");
    console.log(custom);
  });


  $("#generateButton2").on("click", {
    what: "goodbye"
  }, function(event) { // needed here
    var custom = $(this).data("custom");
    console.log(event.data.what + " " + custom); // hello world
  });

  $("#generateButton3").on("click", function() {
    var formdata = $(this).closest("form").serialize();
    console.log(formdata);
  });
  
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" id="generateButton1" data-custom="hello world">Hello world</button>

<button type="button" id="generateButton2" data-custom="world">Goodbye world</button>
<hr/>
Serializing:
<form>
  <input type="text" name="field1" value="f1" /><br/>
  <input type="text" name="field2" value="f2" /><br/>
  <button type="button" id="generateButton3">Click to serialize</button>
</form>

首先,请确保您参考的是 jquery 版本 1.4.3 或更高版本。

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

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