標籤:des style blog http color io os 使用 ar
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>的內容是動態載入的。
[c-sharp] view plaincopy
- <%@ 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中顯示二種下拉式清單當前被選中的內容。顯示出來的是value值。
- $("#ViewDiv").html($("#ddlSel").val() + "-----" + $("#Select1").val());
-
-
- //這裡有一點我要說明的事,我使用的.aspx檔案,這種檔案會在<form>內自己產生自己的幾個<div>,它不是我要取的
- //所以在這裡我加了一個大的div來取我們所要的。
-
- //這裡用filter(fn)來過濾掉裡麵包含ol的項
- $("#all").children("div").filter(function(index) {
- return $("ol", this).size() == 0;
- }).each(function(index){
-
- //這裡顯示出這些div的內容。請注意,在這裡我們用
- //$("div",this).html()這種方法
- alert($("#"+this.id+"").html());
- });
- })
- })
-
- // --></mce:script>
- </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)的使用研究