jQuery ForEach循环? [英] JQuery ForEach loop?
问题描述
嘿,我该怎么说
我表中的Foreach标记,当有人单击它时,我想运行一个函数
类似:
ForEachTag.click
(
function (e)
{
}
)
如果您有这样的表:
<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>
最基本的选择器如下所示:
$('a').click(function(e) {
alert('test!');
return false;
});
这只是将某些内容绑定到文档中的 all 链接.需要更多控制权吗?
$('#test').find('a').click(function(e) {
alert('test!');
return false;
});
这实际上是在说:在id为test
的元素中找到所有<a>
元素,并将此点击处理程序绑定到它上" – jQuery非常强大,因为它以这种方式处理对象集.>
不过,这只是冰山一角!您可以更深入地了解.如果您只想绑定相对于<tr>
在第一个<td>
中出现的<a>
元素,该怎么办?没问题:
$('#test').find('td:nth-child(1) a').click(function(e) {
alert('test');
return false;
});
尽管jQuery确实具有each
函数,该函数可让您遍历一组元素,但在绑定事件时,您几乎不需要它. jQuery喜欢集合,并且只要有必要,它就会对集合元素做任何您要它做的事情.
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)
{
}
)
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.
这篇关于jQuery ForEach循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!