Jquery: How Do I Add A Click Handler To A Class And Find Out Which Element Was Clicked?
Solution 1:
$(".yourclass").click ( function() {
$(this).attr ( "id" ); //S(this) returns the current element
});
and you can code like this
$('.yourclass').bind('click', function() { submit_click($(this)) });
functionsubmit_click(elem)
{
alert ( elem.attr ("id" ) );
}
Edit
$('.clear').bind('click', function() { clear_click($(this)) });
functionclear_click(elem)
{
alert(elem.attr("id"));
}
This will work fine for you.
Solution 2:
Update
To answer your second question:
You can bind a function as a second argument when using the click event, but you cant bind a function and apply arguments. On the other hand, there is no need to send this as an argument to the clear_click function since the this keyword inside the function refers to the element itself:
So this works in your case:
$('.clear').bind('click', clear_click);
functionclear_click() {
alert(this.id);
}
Sending this as an argument is not needed and bad coding:
$('.clear').bind('click', clear_click(this));
In the event handler, the first argument is the event object. You can extract the clicked element from that object using currentTarget or target. In jQuery, this always refers to the currentTarget in the event handler context:
var handler = function(e) {
var id = this.id; // this == e.currentTarget
}
$('submit').click(handler); // .click(fn) is shorthand for .bind('click', fn)More examples:
$('submit').bind('click', function(e) {
console.log(e.target) // the target that was clicked onconsole.log(e.currentTarget) // the element that triggered the clickconsole.log(this) // the same as above
});
Solution 3:
Just add $(this) to your function, You don't need to send any parameters because you are still in the context of the clicked element.
functionsubmit_click() { // notice elementalert($(this).attr('id') + ' clicked');
}
Solution 4:
When you bind a handler to a function, the clicked element will be the first argument
$('.submit-button').click(submit_click);
functionsubmit_click(element){
//element is the .submit-buttom elementalert(element+' was clicked');
alert($(element)+' was clicked');
}
Solution 5:
This should work:
$('.submit-button').bind('click', submit_click($(this)));
functionsubmit_click(element) { // notice elementalert($(element).attr("id") + ' clicked');
}
Post a Comment for "Jquery: How Do I Add A Click Handler To A Class And Find Out Which Element Was Clicked?"