jquery中filter(fn)给出的官方说明是:
筛选出与指定函数返回值匹配的元素集合
这个函数内部将对每个对象计算一次 (正如 ‘$.each‘). 如果调用的函数返回false则这个元素被删除,否则就会保留。
这个说明没有问题,可是给出的例子却有问题。例子是
HTML 代码:
<p><ol><li>Hello</li></ol></p><p>How are you?</p>
jQuery 代码:
$("p").filter(function(index) { return $("ol", this).length == 0; });
结果:
[ <p>How are you?</p> ]
可是大家在试的时候会发现,<p>中是不让放<ol>的,在一些浏览器会报错。
我在自己的一个程序中,用到了filter(fn)这个方法。我就把我使用的例子放出来。
我要做的功能其实很简单,就是要把一个页面中所有的<div>内容显示出来。这里面有些<div>的内容是动态加载的。
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JqeryClick.aspx.cs" Inherits="AJAXEnabledWebApplication1.JqeryClick" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>无标题页</title>
-
-
- <mce:script src="jquery-1.3.2.min.js" mce_src="jquery-1.3.2.min.js" type="text/javascript"></mce:script>
-
-
- <mce:script type="text/javascript"><!--
- $(function(){
- $("#btn").click(function(){
-
-
- $("#ViewDiv").html($("#ddlSel").val() + "-----" + $("#Select1").val());
-
-
-
-
-
-
- $("#all").children("div").filter(function(index) {
- return $("ol", this).size() == 0;
- }).each(function(index){
-
-
-
- alert($("#"+this.id+"").html());
- });
- })
- })
-
- </head>
- <body>
- <form id="form1" runat="server">
- <div id="all">
- <div id="one">
- <asp:DropDownList ID="ddlSel" runat="server">
- <asp:ListItem Value="1">第一项</asp:ListItem>
- <asp:ListItem Value="2">第二项</asp:ListItem>
- </asp:DropDownList>
- <select id="Select1">
- <option value="3">第三项</option>
- <option value="4">第四项</option>
- </select>
- <input id="btn" type="button" value="显示信息" /></div>
-
- <div id="ViewDiv"></div>
-
-
-
- <div id="2"><ol><li>Hello</li></ol></div><div id="1">How are you?</div>
-
- </div>
- </form>
- </body>
- </html>
jquery中filter(fn)的使用研究
原文:http://www.cnblogs.com/ranzige/p/4026729.html