开发者

How to pass parameter to click event in Jquery

开发者 https://www.devze.com 2023-04-03 09:06 出处:网络
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!

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="displa开发者_如何学Cy(this.id)" />


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);" />


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


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


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

no need to wrap it in a jquery object

0

精彩评论

暂无评论...
验证码 换一张
取 消