JQuery遍历

 
遍历



现在,您已经学会如何搜索和过滤页面上的所有元素,接下来需要一种高效的方法来遍历结果,进一步处理元素。自然,jQuery 提供了几种遍历搜索结果的方法。



第一个也是最常用的遍历方法是 each() 函数。这和 “for

 loop” 的功能是一样的,遍历每个元素并通过迭代递增元素。此外,循环中的每个元素的引用可以通过 “this

”(用于一般的 JavaScript 语法)或 $(this

)(用于 jQuery 命令)来实现。



让我们看看下面的示例。



清单 10. each 循环

 

JavaScript代码

// Will loop through each <p> tag on the page.  notice the use of the   


// inline function here -- this is analogous with the anonymous classes in Java.   


// You can either call a separate function, or write an inline function like this.   


  

var

 increment = 1;   

$("p"
).each(function

(){   

  

    // now add a paragraph count in front of each of them.  Notice how we use the   


    // $(this) variable to reference each of the paragraph elements individually.   


  

    $(this

).text(increment + ". "
 + $(this

).text());   

    increment++;   

});   

因为搜索结果存储在一个数组中,您肯定希望函数遍历该数组,就像处理其他编程语言的数据对象一样。因此,要查找一个给定搜索结果的长度,则可以在该数组上调用 $().length。清单 11 展示了更多的数组遍历函数,可适用于其他编程语言的数组遍历。



清单 11. 其他数组函数 

 

JavaScript代码

// the eq() function lets you reference an element in the array directly.     


// In this case, it will get the 3rd paragraph (0 referenced of course) and hide it   


$("p"
).eq(2).hide();   

  

// The slice() function lets you input a start and an end index in the array, to    


// create a subset of the array.  This will hide the 3rd through 5th paragraphs on the   


// page   


$("p"
).slice(2,5).hide();   

除了这些数组遍历函数之外,jQuery 还提供了一些函数,使您可以查找嵌套在搜索词周围的元素。为什么这很有用呢?例如,我们常常需要在图片的旁边嵌入一个文本标签,或在表单元素旁边嵌入一个错误消息。使用这些命令可以查找特定的表单元素,然后通过将表单元素放置在下一个元素(span 标记)中,把该错误消息直接放置在表单元素旁边。清单 12 显示了这种设计的一个示例:



清单 12. 示例 next() 函数 

 

JavaScript代码

<input class

=validate type=text>   

  

function

 validateForm()   

{   

    $(".validate:text"
).each(function

(){   

    if

 ($(this

).val()==""
)   

    //  We'll loop through each textfield on the page with a class of "validate"   


    //  and if they are blank, we will put text in the <span> immediately afterwards   


    //  with the error message.   


  

        $(this

).next().html("This field cannot be blank"
);   

});   

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值