2011-09-08 27 views
12

Quiero cambiar el siguiente JS a Jquery. Pero no sé cómo pasar el parámetro al evento click en Jquery. ¿Alguien puede ayudarme, gracias?Cómo pasar el parámetro al evento click en 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)" /> 

Respuesta

8

Usted no tiene que pasar el parámetro, se puede conseguir usando .attr() método

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

hay necesidad de envolverlo en un objeto jQuery

20

mejor enfoque:

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

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

Pero, si necesita realmente para hacer la línea de controlador click, esto va a funcionar:

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

como dice DOC, puede pasar datos al controlador como el próximo:

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