[jquery] How to pass parameter to click event in Jquery

I want to change the following JS to Jquery. But I don't know how to pass parameter to click event in Jquery. Can anyone help me, thanks!

<script type="text/javascript">

function display(id){

    alert("The ID is "+id);
    }
</script>

<input id="btn" type="button" value="click" onclick="display(this.id)" />

This question is related to jquery

The answer is


As DOC says, you can pass data to the handler as next:

// say your selector and click handler looks something like this...
$("some selector").on('click',{param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);

    // access element's id where click occur
    alert( event.target.id ); 
}

 $('elements-to-match').click(function(){
        alert("The id is "+ this.id );
    });

no need to wrap it in a jquery object


Better Approach:

<script type="text/javascript">
    $('#btn').click(function() {
      var id = $(this).attr('id');
      alert(id);
    });
</script>

<input id="btn" type="button" value="click" />

But, if you REALLY need to do the click handler inline, this will work:

<script type="text/javascript">
    function display(el) {
        var id = $(el).attr('id');
        alert(id);
    }
</script>

<input id="btn" type="button" value="click" OnClick="display(this);" />

You don't need to pass the parameter, you can get it using .attr() method

$(function(){
    $('elements-to-match').click(function(){
        alert("The id is "+ $(this).attr("id") );
    });
});