2010年9月1日 星期三

jQuery神奇的選擇器(Selector)

就像正規運 算式(Regular Expression)的Pattern match一般,jQuery使用了CSS(Cascading Style Sheet)、XPath(XML Path Language)與自訂等三大類的選擇器(Selector)當做$( )函數的參數,讓我們由複雜多樣的DOM結構裡,快速的找出符合樣式的要素。

使用選擇器的三個基本格式是:
序 格式        範例        說明
1 $("HTML標籤")   $("div")      傳回表示所有div要素的jQuery物件
2 $("#要素的ID")   $("#linksLeft")   傳回表示<div id="linksLeft">要素的jQuery物件
3 $(".要素的類別")   $(".blogname")  傳回<div class="blogname">要素的jQuery物件

jQuery 怎麼用來「快速選取元素」並且「做一些事情」呢?請看看程式碼:
$("div").addClass("special");

$("div")        解釋:選取所有 <div>
$("#body")       解釋:選取 id 為 body 的元素
$("div#body")     解釋:選取 id 為 body 的 <div>
$("div.contents p")   解釋:選取 class 為 contents 的 <div> 所包住的所有下層的 <p>
$("div > div")     解釋:選取被 <div> 包住的下一層 <div>
$("div:has(div)")    解釋:和前一個範例相反,這邊是選取至少有包住一個 <div> 的 <div>

[範例1] 選取所有有 target 屬性的 <a>,並且在其節點下加入一段文字
$("a[target]").append(" (Opens in New Window)");  

這是一段原始的 HTML
jsGears  
Google
Amazon

選取有 target 屬性並加入文字後的結果:
jsGears  
Google (Opens in New Window)
Amazon (Opens in New Window)

[範例2] 選取 id 為 body 的元素,並且修改兩個 css 屬性。
$("#body").css({   
border: "1px solid green",
height: "40px"
});

這是一段原始的 HTML :

...

選取 id 為 body 的元素並修改 css 後的結果(示意):

...

[範例3] 在網頁上的表單送出時加入一個判斷,如果 username 這個欄位是空值的話,就顯示 help 這個區塊內的文字。
$("form").submit(function() {   
if ($("input#username").val() == "")
$("span.help").show();
});

可作用在類似以下的 HTML,一開始 span.help 是隱藏的,如果沒有輸入 username,才會顯示:
  



這個欄位必填喔

[範例4] 當 user 點選 id 為 open 的連結時,顯示 id 為 menu 的區塊,並回傳 false 避免瀏覽器真的換頁。
$("a#open").click(function() {   
$("#menu").show();
return false;
});

可作用在類似以下的 HTML:
  
控制面板

[範例5] 將 id 為 menu 的區塊以下拉布幕的動態效果快速顯示:
$("#menu").slideDown("fast");

可作用在類似以下的 HTML,原本隱藏的選單會以動態下拉的方式顯示出來:
  

[範例6] 將所有的 <div> 漸變為寬 300px、文字與邊界寬 20px
$("div").animate({   
width: '300px',
padding: '20px'
}, 'slow');

可作用在類似以下的 HTML:

Hello world!

PS. jQuery 核心程式的 animate 函數能改變的元素屬性並不多,但是可以透過其他 plugin 提供更多的動態效果。

[範例7] 動態效果的 callback 的範例,將所有的 <div> 以 0.5 秒的動態效果隱藏後,再以 0.5 秒的動態效果顯示。hide() 的第二個參數就是一個 callback 函數,其中 $(this) 是原本程式所處理的各個元素。
$("div").hide(500, function(){   
// $(this) 是每一個各別的 <div>
$(this).show(500);
});

可作用在類似以下的 HTML:

Hello world!


jsGears.com!

[範例8] 取得 sample.html 並將找出文件內所有 <div> 下一層的 <h1> 填入原本文件 id 為 body 的元素內
$("#body").load("sample.html div > h1");  

這是一段原始的 HTML :

sample.html 的片段:

Hello world!


This is H2


jsGears.com!



執行程式碼之後的結果:

Hello world!


jsGears.com!



[範例9] 透過 getJSON() 取得 JSON 格式的資料,並透過 callback 函數處理資料
$.getJSON("test.json", function(data){   
for (var idx in data)
$("#menu").append("
  • " + data[idx] + "
  • ");
    });

    這是一段原始的 HTML:
      

    test.json 的內容:
    [   
    "Hello world!",
    "jsGears.com!"
    ]

    執行程式碼之後的結果:
      

    [範例10]抓取DIV內容
    onclick="addition('DivSh_Year');"


    [範例11]抓取DIV內容
    onclick="addition(DivSh_Year);"

    jQuery教學-SliderGallery滑動式相本特效應用



    CSS部分
    body{font-family:Arial, Helvetica, sans-serif;}
    ul ,li{ margin:0; padding:0; list-style-type: none; float:left;}
    #showbox{width:360px; border:solid 1px #eee;}
    #showImg , #showImg table{width:360px; height:300px;}
    #imgList{margin-top:10px; margin-left:3px; padding-bottom:10px; overflow:auto;}
    #imgList span{float:left; display:block; width:22px; margin:2px; line-height:50px;}
    #list{position:relative; float:left; width:350px; height:60px;}
    #list img{width:40px; height:40px;}
    #list{width:300px; float:left; margin:0 2px; overflow:hidden;}
    #list ul{ position:absolute; left:0; top:0; white-space: nowrap;/* 不斷行 */}
    #list ul li{
    display: inline; /* 水平排列 */
    margin:0 4px;
    padding:5px;
    border:solid 1px #eee;
    }
    #list ul li.on{border:solid 2px #ccc;}
    #list ul li img {display: inline-block; /* 水平內顯示為區塊 */}
    /* 秀大圖 */
    #imgB{border:solid 7px #fff;}
    /* 滑入顯示圖片區塊 */
    #overImg{position:absolute; top:-99999; left:-99999; display:none; z-index:100; border:solid 5px #666; padding:5px; background:#fff;}

    HTML的部分







































    轉載自 http://www.minwt.com/?p=1406
    如需範例或DEMO請至原網站瀏覽

    jQuery-將網頁元素名稱標示出來


    不知有沒有人跟我有一樣的困擾? 步入中年後,腦容量似有變小趨勢,每次寫網頁Client Script時,<input>, <select>的欄位名稱老記不住,要用時總是要回HTML Source或用IE Dev Tools去查,查完了一轉頭又忘了,再不然就是切換回Script Editor時搞不清楚剛才寫到哪裡。幾番折騰下來,效率很差,心情很糟。(老了,不中用了~~ 不中用了~~ 不~中~用~了了了了~~~)

    於是我寫了以下的jQuery Plugin,試圖把所有的輸入元素id直接顯示在網頁上,方便對照,也試圖挽救我岌岌可危的事業。
    $.fn.showElemId = function(bgc, fc) {
    return this.each(function() {
    var $elem = $(this);
    //if (!$elem.is(":visible")) return;
    var pos = $elem.offset();
    var html = "" +
    (this.id || "----") +
    "
    ";
    $("body").append(html);
    });
    };
    /* 使用範例: $(":text,select").showElemId(); */

    用Hotmail的註冊畫面做個示範(只查:text,select,不包含:button,:password),如下圖所示,輸入欄位元素名稱一目瞭然,列印出來,就不用每次去HTML Source裡找半天了,真是中年程式開發人員的福音呀

    轉載自 http://blog.darkthread.net/blogs/darkthreadtw/archive/2009/10/13/mark-element-id-with-jquery.aspx

    [jQuery] 如何自動取得所有前端 JavaScript 錯誤以提升網站品質

    這個需求透過 jQuery 來做最方便了,透過 error(fn) 事件即可達成此一目標:
    $(window).error(function(msg, url, line){  
    jQuery.post("/js_error_log.ashx", { msg: msg, url: url, line: line });
    });

    透過這個技巧即可有效獲得即時的前端資訊,看你要儲存到資料庫、EventLog、File、或郵寄出來都可以,不過唯一要小心的地方是當錯誤非常多時,這個錯誤追蹤的量可能會非常大,這時要特別注意程式的寫法,不要因為前端的錯誤槁掛了你的伺服器,而且有查到錯誤就要立即處理,降低錯誤發生的次數與提升網站品質。

    C# 動態新增User Control,並設定屬性值與取屬性值

    新增一個UserControl
    ascx:
    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="CustIDName.ascx.cs" Inherits="UserControl_CustIDName" %>
    <%@ Register Assembly="Joey" Namespace="Joey" TagPrefix="cc1" %>



    .ascx.cs
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    public partial class UserControl_CustIDName : System.Web.UI.UserControl
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public string CustID
    {
    get
    { return this.JoeyTextBox1.mTextBox.Text; }
    set
    { this.JoeyTextBox1.mTextBox.Text = value; }

    }
    public string CustName
    {
    get
    { return this.JoeyTextBox2.mTextBox.Text; }
    set
    { this.JoeyTextBox2.mTextBox.Text = value; }

    }
    public string ValidationGroup
    {
    get
    { return this.JoeyTextBox1.ValidationGroup; }
    set
    {
    this.JoeyTextBox1.ValidationGroup = value;
    this.JoeyTextBox2.ValidationGroup = value;
    }
    }
    }

    接著我們在一個空白頁面上,加入一個panel
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    public partial class LoopAddUserControl : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    this.DropDownList1.Items.Add(new ListItem("user control index"));
    for (int i = 0; i < 10; i++)
    {
    this.DropDownList1.Items.Add(new ListItem(i.ToString()));
    }
    }

    for (int index = 0; index < 10; index++)
    {
    Control ctlNewTrial = this.Page.LoadControl("UserControl/CustIDName.ascx");
    SetUserControlProperty(ctlNewTrial, "ID", "Usrctrl" + index.ToString());
    SetUserControlProperty(ctlNewTrial, "CustID", index.ToString());
    SetUserControlProperty(ctlNewTrial, "CustName", index.ToString()+":name");

    this.Panel1.Controls.Add(ctlNewTrial);
    Label br = new Label();
    br.Text = "index=" + index.ToString()+ "
    ";
    this.Panel1.Controls.Add(ctlNewTrial);
    this.Panel1.Controls.Add(br);
    }
    }

    ///
    /// 設定user control的屬性值
    ///

    /// usercontrol by page.loadcontrol()
    /// usercontrol's property
    /// setting property value
    ///
    public void SetUserControlProperty(Control vobjControl, string vstrPropertyName, object vobjValue)
    {
    vobjControl.GetType().GetProperty(vstrPropertyName).SetValue(vobjControl, vobjValue, null);
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
    ASP.usercontrol_custidname_ascx usrctl1 = (ASP.usercontrol_custidname_ascx)this.Panel1.FindControl("Usrctrl" + this.DropDownList1.SelectedValue);
    if (usrctl1 != null)
    {
    this.TextBox1.Text = usrctl1.CustID;
    this.TextBox2.Text = usrctl1.CustName;
    }
    else
    {
    this.TextBox1.Text = string.Empty;
    this.TextBox2.Text = string.Empty;
    }
    }
    }

    參考文件
    [ASP.NET]動態Load UserControl – part 2 - In 91- 點部落
    WebUserControl之間值得傳遞(使用Interface) - topcat 姍舞之間的極度凝聚- 點部落
    [ASP.NET]動態新增User Control,並設定屬性值與取屬性值 - In 91- 點部落

    2010年8月26日 星期四

    jQuery 外掛 - The Silky Smooth Marquee 文字跑馬燈

    (1)官方網站:remy sharp's b:log
    (2)外掛程式下載:http://remysharp.com/2008/09/10/the-silky-smooth-marquee/
    (3)官方範例:http://remysharp.com/demo/marquee.html

    javascript 垂直輪播(跑馬燈、vertical carousel)

    首先設定一個style(也可以直接放在標籤裡)
    .ann{overflow:hidden;height:20px;}

    這是html的部份,包在外面的div高度跟裡面個別的div高度設定成一樣
    <div id="ann_box" class="ann" style="width:100px;">
    <div id="a1" class="ann"><a href="exp01.php" >exp01</a></div>
    <div id="a2" class="ann"><a href="exp02.php" >exp02</a></div>
    <div id="a3" class="ann"><a href="exp03.php" >exp03</a></div>
    <div id="a4" class="ann"><a href="exp04.php" >exp04</a></div>
    <div id="a5" class="ann"><a href="exp05.php" >exp05</a></div>
    </div>

    這是javascript的部份
    function slideLine(box,stf,delay,speed,h)
    {
    //取得id
    var slideBox = document.getElementById(box);
    //預設值 delay:幾毫秒滾動一次(1000毫秒=1秒)
    // speed:數字越小越快,h:高度
    var delay = delay||1000,speed = speed||20,h = h||20;
    var tid = null,pause = false;
    //setInterval跟setTimeout的用法可以咕狗研究一下~
    var s = function(){tid=setInterval(slide, speed);}
    //主要動作的地方
    var slide = function(){
    //當滑鼠移到上面的時候就會暫停
    if(pause) return;
    //滾動條往下滾動 數字越大會越快但是看起來越不連貫,所以這邊用1
    slideBox.scrollTop += 1;
    //滾動到一個高度(h)的時候就停止
    if(slideBox.scrollTop%h == 0){
    //跟setInterval搭配使用的
    clearInterval(tid);
    //將剛剛滾動上去的前一項加回到整列的最後一項
    slideBox.appendChild(slideBox.getElementsByTagName(stf)[0]);
    //再重設滾動條到最上面
    slideBox.scrollTop = 0;
    //延遲多久再執行一次
    setTimeout(s, delay);
    }
    }
    //滑鼠移上去會暫停 移走會繼續動
    slideBox.onmouseover=function(){pause=true;}
    slideBox.onmouseout=function(){pause=false;}
    //起始的地方,沒有這個就不會動囉
    setTimeout(s, delay);
    }
    //網頁load完會執行一次
    //五個屬性各別是:外面div的id名稱、包在裡面的標籤類型
    //延遲毫秒數、速度、高度
    slideLine('ann_box','div',2000,25,20);

    這是範例 http://ex.hsin.tw/exp06.php

    2010年8月25日 星期三

    JavaScrip 自動輪播頁籤 ( IE 與 Mozilla 通用 )

    CSS
    .ImgTab {cursor:hand} ←這行可有可無,不影響程式執行
    .MsgHide {height:174px;border:1px solid #aaa;padding:10px;font:normal 12px 細明體;display:none}

    HTML ( 以下為完整頁籤架構 )
    <table border="0" cellpadding="0" cellspacing="0">
    <tr>
    <td><img name="Tag_COMM" class="ImgTab" src="Tab_Img10.gif" onmouseover="Rot_Msg(1)" onmouseout="Rot_Msg()" onclick="Pause_Msg()"></td>
    <td><img name="Tag_COMM" class="ImgTab" src="Tab_Img20.gif" onmouseover="Rot_Msg(2)" onmouseout="Rot_Msg()" onclick="Pause_Msg()"></td>
    <td><img name="Tag_COMM" class="ImgTab" src="Tab_Img30.gif" onmouseover="Rot_Msg(3)" onmouseout="Rot_Msg()" onclick="Pause_Msg()"></td>
    </tr>
    <tr><td colspan="3">
    <div id="Tag_IE" name="Tag_FF" class="MsgHide">
    訊息內容...
    </div>
    <div id="Tag_IE" name="Tag_FF" class="MsgHide">
    訊息內容...
    </div>
    <div id="Tag_IE" name="Tag_FF" class="MsgHide">
    訊息內容...
    </div>
    </td></tr>
    </table>

    JavaScript ( 更改輪播速度,範例為3000毫秒 )
    Msg_Timer=setTimeout("Rot_Msg()",3000);