How can I bind an event handler to an instance in jQuery?

前端 未结 2 1560
一个人的身影
一个人的身影 2021-01-27 22:53

I am trying to bind an event to a \"method\" of a particular instance of a Javascript \"class\" using jQuery. The requirement is that I in the event handler should be able to us

相关标签:
2条回答
  • 2021-01-27 23:27

    Just use an anonymous function:

    $("#myButton").click(function() { myCar.drive(); });
    
    0 讨论(0)
  • 2021-01-27 23:30

    Try this :

    $("#myButton").each(function() {
    
    var $btn = $(this);
    
        $btn.on('click',function(){
    
         // Do whatever you want.
    
        });
    });
    

    Here you first create a loop to target all #myButton elements (Which is wrong in your example, You should be using Class instead) like:

    $(".myButton").each(...
    

    Then we attach the click event handler to all of them.

    0 讨论(0)
提交回复
热议问题