遍历
Prev Chapter 3. jQuery 基础 Next

遍历

一旦你拥有jQuery选择器,你就能使用它作为起始点去发现其它的元素。

jQuery遍历方法完整的文档,请访问http://api.jquery.com/category/traversing/.

Note

在遍历很长的文档时要小心 -- 完整的遍历有必要保留你的文档结构,除非你从服务端到客户端创建了完整应用,否则一些事将很难保证。一个或两个步骤的遍历是好的,但是当你从一个容器到另一个容器时需要避免遍历的发生。

Example 3.24. 使用遍历方法围绕DOM移动

$('h1').next('p');
$('div:visible').parent();
$('input[name=first_name]').closest('form');
$('#myList').children();
$('li.selected').siblings();

你也能通过一个使用$.fn.each的选择器对所有元素进行迭代,为每个元素都运行一次函数。函数将接收当前元素的索引和带有参数的DOM元素。在函数内部,默认情况下 DOM 元素作为this是可用的。

Example 3.25. 通过选择器迭代

$('#myList li').each(function(idx, el) {
    console.log(
        'Element ' + idx + 
        'has the following html: ' +
        $(el).html()
    );
});


Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.


Prev Up Next
属性 Home 操作元素