jQuery 如何使用jQuery检测点击了哪个按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7919328/
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-27 00:27:17  来源:igfitidea点击:

how to detect which button is clicked using jQuery

jqueryhtml

提问by eagle

how to detect which button is clicked using jQuery

如何使用jQuery检测点击了哪个按钮

<div id="dBlock">
 <div id="dCalc">
  <input id="firstNumber" type="text" maxlength="3" />
  <input id="secondNumber" type="text" maxlength="3" />
  <input id="btn1" type="button" value="Add" />
  <input id="btn2" type="button" value="Subtract" />
  <input id="btn3" type="button" value="Multiply" />
  <input id="btn4" type="button" value="Divide" />
 </div>
</div>

Note: above "dCalc" block is added dynamically...

注意:上面的“dCalc”块是动态添加的...

回答by genesis

$("input").click(function(e){
    var idClicked = e.target.id;
});

回答by RoccoC5

$(function() {
    $('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); });
});

回答by Esailija

Since the block is added dynamically you could try:

由于块是动态添加的,您可以尝试:

jQuery( document).delegate( "#dCalc input[type='button']", "click",
    function(e){
    var inputId = this.id;
    console.log( inputId );
    }
);

demo http://jsfiddle.net/yDNWc/

演示http://jsfiddle.net/yDNWc/

回答by Highway of Life

jQuery can be bound to an individual input/button, or to all of the buttons in your form. Once a button is clicked, it will return the object of that button clicked. From there you can check attributes such as value...

jQuery 可以绑定到单个输入/按钮,或绑定到表单中的所有按钮。单击按钮后,它将返回单击该按钮的对象。从那里您可以检查属性,例如值...

$('#dCalc input[type="button"]').click(function(e) {
    // 'this' Returns the button clicked:
    // <input id="btn1" type="button" value="Add">
    // You can bling this to get the jQuery object of the button clicked
    // e.g.: $(this).attr('id'); to get the ID: #btn1
    console.log(this);

    // Returns the click event object of the button clicked.
    console.log(e);
});