Reputation:
Hey, how can I say the following
Foreach tag in my table, when someone clicks it I want to run a function
so something like:
ForEachTag.click
(
function (e)
{
}
)
Upvotes: 1
Views: 11106
Reputation: 45721
Well, it depends on how you want to do it. Basically, you have two options:
To add the same click-listener to multiple tags, do this:
$(selectorForElements).click(function (e) {
// Click handling code here.
// e is the event object
// this inside the handler refers to the element that was clicked.
});
To use event delegation, do something like this:
$(selectorForParentElement).click(function (e) {
var target = $(e.target());
// Checked if we clicked the "correct" element, else traverse
// up the DOM tree until we find the parent element we ARE interested in.
if(!target.is(whatYouAreInterestedIn)) {
target = target.parent(whatYouAreInterestedIn).eq(0);
}
// Your click handler for the target goes here
});
When possible it is better to use event delegation since it binds fewer listeners and thus consumes less memory and increases execution speed, especially on older browsers. You can read some about event delegation here:
Upvotes: 0
Reputation: 488384
If you have a table like this:
<table id='test'>
<tr>
<td><a href="#">test</a></td>
<td>Hi</td>
</tr>
<tr>
<td><a href="#">test1</a></td>
<td>Hi</td>
</tr>
</table>
The most basic selector is going to look like this:
$('a').click(function(e) {
alert('test!');
return false;
});
This is simply binding something to all the links in the document. Want more control?
$('#test').find('a').click(function(e) {
alert('test!');
return false;
});
Which is essentially saying: "find me all the <a>
elements inside the element with id of test
and bind this click handler to it" - jQuery is so powerful because it handles sets of objects this way.
This is just the tip of the iceberg, though! You can get much more in-depth. What if you only want to bind the <a>
elements that appear in the 1st <td>
relative to the <tr>
? No problem:
$('#test').find('td:nth-child(1) a').click(function(e) {
alert('test');
return false;
});
Although jQuery does have an each
function that lets you iterate through a set of elements, when it comes to binding events you will rarely need it. jQuery loves sets and will do anything you ask it to to a set of elements if it makes any sense.
Upvotes: 5