jQuery Button Click 'this'

后端 未结 3 736
走了就别回头了
走了就别回头了 2021-01-25 16:58

Say we have a simple event button handler:

$( \"#aButton\" ).click(function() {
   console.log( \"tile\" + this.val() + \"clicked\" );
});

I re

相关标签:
3条回答
  • 2021-01-25 17:05

    Use $(this) to obtain the clicked element.

    $("#aButton").click(function() {
        console.log("tile " + $(this).val() + " clicked");
    });
    

    In addition, you can note that $(this)[0] === this

    this should can be used when using built in JavaScript methods, such as .addEventListener(). Using this in this context will return the Node that triggered the event.

    0 讨论(0)
  • 2021-01-25 17:05

    The object that you clicked can be referred by this, so saying this.id will give you button's id "aButton". However, if you want to use jQuery's methods then you have to say $(this).attr('id') which will again give you "aButton". So you do have different mechanisms available to you but if you are using jQuery, it is preferable to use jQuery methods.

    0 讨论(0)
  • 2021-01-25 17:23

    this is the raw DOM element. You have to wrap it in a jQuery object if you want to use jQuery functions on it.

    console.log( "tile" + $(this).val() + "clicked" );
    //                    ^^^^^^^^^^^^^
    

    Inputs have a property called value that does the same. So you can use it on raw DOM inputs like this:

    console.log( "tile" + this.value + "clicked" );
    //                    ^^^^^^^^^^
    
    0 讨论(0)
提交回复
热议问题