2011-10-27 134 views
9

la forma de detectar qué botón se hizo clic con jQuerycómo detectar qué botón se hizo clic con 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> 

Nota: por encima de "Dcalc" se añade bloque de forma dinámica ...

Respuesta

31
$("input").click(function(e){ 
    var idClicked = e.target.id; 
}); 
5
$(function() { 
    $('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); }); 
}); 
1

Dado que el bloque se agrega dinámicamente puede intentar:

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

demo http://jsfiddle.net/yDNWc/

1

jQuery se puede vincular a una entrada/botón individual, oa todos los botones en su formulario. Una vez que se hace clic en un botón, devolverá el objeto de ese botón al que se hizo clic. Desde allí puede verificar atributos como el valor ...

$('#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); 
}); 
+0

Técnicamente, 'e' representa el objeto de evento click, no el objeto de botón. – Blazemonger

+0

Tiene razón, actualizó la respuesta. –

+0

@ mblase75, en realidad el objeto de evento click es 'e.originalEvent',' e' es un objeto personalizado generado por jQuery que tiene propiedades de "exploración cruzada" por conveniencia, y no incluye algunas cosas que están en el 'e.originalEvent' : P – Esailija

Cuestiones relacionadas