jquery API學習(2)
最近比較忙,但是每天網上還是的堅持學點,不積小流,無以成江河。今天學jQuery對象訪問:
1.each(callback) 該方法以每一個匹配的元素作為上下文來執行一個函數,
在每次執行函數時,都會給函數傳遞一個表示作為執行環境的元素在匹配的元素集合中所處位置的數字值作為參數(從0開始的int)
返回‘false’將停止循環(相當于普通循環中使用的‘break’)
返回‘true’將跳至下一個循環,(相當于在普通的循環中使用‘continue’)
參數:callback(function)
e.g1
<img/><img/>
jQuery代碼:
$('img').each(function(){
this.src="test"+i+".jpg";
});
e.g2
<button>Change colors</button> <span></span> <div></div> <div></div> <div></div> <div></div> <div id="stop">Stop here</div> <div></div> <div></div> <div></div>
jQuery代碼:
$('button').click(function(){
$('div').each(function(index,domEle){//domEle ==this
$(domEle).css('backgroundColor',"yellow");
if($(this).is("#stop")){
$("span").text("stopped at div index #"+index);
return false;}
});});
2.size() 和length
都可以勇于得到jQuery對象中元素的個數,
返回: Number
e.g1
<img src="test1.jpg"/><img src="test2.jpg"/>
jQuery代碼:
$("img").size();
e.g2
同理:$("img").length;
3.get()取得所有匹配的DOM元素集合
返回:Array<Element>
e.g1
<img src="test1.jpg"/><img src="test2.jpg"/>
jQuery代碼:
$("img").get().reverse();
result:
[<img src="test1.jpg"/><img src="test2.jpg"/>]
4.get(index)
取得其中一個匹配元素,index表示取得第幾個匹配的元素
返回值:Element
HTML代碼:
<img src="test1.jpg"/><img src="test2.jpg"/>
jQuery代碼:
$("img").get(0);
result:
[<img src="test1.jpg"/>]
5.index(subject)
搜索與參數表示的對象匹配的元素,并返回相應元素的索引值,
如果哦找到了匹配的元素,從0開始返回;如果沒有找到匹配的元素,返回-1
返回值;
Number
參數:
subject(Element)
e.g1返回id值為foobar的元素的索引值
<div id="foobar"><div></div><div id="foo"></div></div>
jQuery代碼:
$("div").index($("#foobar")[0]) //0
$("div").index($('#foo')[0]) // 2
$("div").index($('#foo')) // -1
備注:
今天在瀏覽別人博客的時候看到的,收藏。
有時候,我們頁面當中并不需要把要用到的JS全部加載出來,
這會使頁面加載時速度變慢~~~如果能按需加載,那能提高不少性能...也能節約不少流量~~~給用戶帶來好的體驗~~
好比說,當某個JS效果是觸發事件才顯示的...這個效果被封閉在一個JS中,,我想大家經常這樣做吧~~這時候,我們能按需加載那就不必在頁面載入時去加載JS文件~~~這在jquery插件中很多。
用法:
1 , 當在需要的時候再加載所需的javascript和css文件。
$.include('file/test.js')或$.include('file/test.css')
2, 當然若你一次想加載多個文件你也可以這樣寫:
$.include(['file/test.js','file/test.css'])。
3, 因為這兩個文件的路徑相同,所以可以先指定路徑再加載所有文件:
$.ImportBasePath = 'file/';
$.include(['test.css','test.js']);
4, 你還可以加載完文件后執行回調函數
$.include("file/test.css",function(){
alert("加載css后執行");
});
插件下載地址:http://www.94this.com.cn/myCode/jqueryIncludefile/jqueryIncludefile.rar
注:jquery 自帶了有一個異步請求的方法,$.getScript ,可以異步加到JS并執行
jQuery.getScript(url,[callback])
返回值
XMLHttpRequest
參數
url (String) : 待載入 JS 文件地址。
callback (Function) : (可選) 成功載入后回調函數。
示例
載入 jQuery 官方顏色動畫插件 成功后綁定顏色變化動畫。
HTML 代碼:
<div class="block"></div>
jQuery 代碼:
function(){
$("#go").click(function(){
$(".block").animate( { backgroundColor: 'pink' }, 1000)
.animate( { backgroundColor: 'blue' }, 1000);
});
});
加載并執行 test.js。
jQuery 代碼:
加載并執行 test.js ,成功后顯示信息。
jQuery 代碼:
alert("Script loaded and executed.");
});
posted on 2008-12-02 23:56 forgood 閱讀(803) 評論(0) 編輯 收藏 所屬分類: jquery