简体   繁体   中英

How can I send custom data to JQuery click event?

I have this JQuery click event:

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);
    });

How could I possibly send custom data to this event, for example print {key: "hello world"}? Is it at all possible?

Note: In my custom made working environment jq() is $() or jquery().

Note: jQuery docs say that eventData can be anything, here's the official doc: https://api.jquery.com/click/ :)

Normally you would use the data attribute for this and grab it with

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

using

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

You are referring to event.data which is sent at bind time

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

Examples

 $(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> 

You can't but a way around is to have a data attribute in your html and get that attribute on click of that element.

eg:

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

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

First, make sure you are reference jquery version 1.4.3 or higher.

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

All data passed in this eventData signature are accessible in the event.data object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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