jQuery 如何将参数传递给Jquery中的点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7350860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:44:00  来源:igfitidea点击:

How to pass parameter to click event in Jquery

jquery

提问by Acubi

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!

我想将以下 JS 更改为 Jquery。但我不知道如何在 Jquery 中将参数传递给点击事件。谁能帮帮我,谢谢!

<script type="text/javascript">

function display(id){

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

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

回答by jmar777

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

回答by Eugen Konkov

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

正如DOC所说,您可以将数据传递给处理程序,如下所示:

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

回答by Ortiga

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

你不需要传递参数,你可以使用.attr()方法来获取它

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

回答by Pantelis

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

no need to wrap it in a jquery object

无需将其包装在 jquery 对象中