jquery 學(xué)習(xí)之一 對象訪問
each()
each(callback)
而且,在每次執(zhí)行函數(shù)時(shí),都會給函數(shù)傳遞一個(gè)表示作為執(zhí)行環(huán)境的元素在匹配的元素集合中所處位置的數(shù)字值作為參數(shù)(從零開始的整形)。
返回 'false' 將停止循環(huán) (就像在普通的循環(huán)中使用 'break')。返回 'true' 跳至下一個(gè)循環(huán)(就像在普通的循環(huán)中使用'continue')。Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set (integer, zero-index).
Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).返回值
jQuery
參數(shù)
callback (Function) : 對于每個(gè)匹配的元素所要執(zhí)行的函數(shù)
示例
迭代兩個(gè)圖像,并設(shè)置它們的 src 屬性。注意:此處 this 指代的是 DOM 對象而非 jQuery 對象。
HTML 代碼:
jQuery 代碼:
this.src = "test" + i + ".jpg";
});
結(jié)果:
如果你想得到 jQuery對象,可以使用 $(this) 函數(shù)。
jQuery 代碼:
$(this).toggleClass("example");
});
你可以使用 'return' 來提前跳出 each() 循環(huán)。
HTML 代碼:
<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; } });});--------------------------------------------------------------------------------------------------------------------------------
size()
返回值
Number
示例
計(jì)算文檔中所有圖片數(shù)量
HTML 代碼:
jQuery 代碼:
結(jié)果:
length
返回值
Number
示例
計(jì)算文檔中所有圖片數(shù)量
HTML 代碼:
jQuery 代碼:
結(jié)果:
get()
取得所有匹配的 DOM 元素集合。
如果你想要直接操作 DOM 對象而不是 jQuery 對象,這個(gè)函數(shù)非常有用。
返回值
Array<Element>
示例
選擇文檔中所有圖像作為元素?cái)?shù)組,并用數(shù)組內(nèi)建的 reverse 方法將數(shù)組反向。
HTML 代碼:
jQuery 代碼:
結(jié)果:
get(index)
返回值
Element
參數(shù)
index (Number) :取得第 index 個(gè)位置上的元素
示例
HTML 代碼:
jQuery 代碼:
結(jié)果:
index(subject)
返回值
Number
參數(shù)
subject (Element) : 要搜索的對象
示例
返回ID值為foobar的元素的索引值值。
HTML 代碼:
jQuery 代碼:
結(jié)果:
相關(guān)文章
JQuery擴(kuò)展插件Validate 2通過參數(shù)設(shè)置驗(yàn)證規(guī)則
在前面示例中使用的的方法簡單方便,但沒有完全將js與頁面結(jié)構(gòu)完全分離,也就是說js依賴了class,下面通過validate()方法的參數(shù)設(shè)置驗(yàn)證規(guī)則將js與頁面結(jié)構(gòu)完全分離2011-09-09推薦40個(gè)簡單的 jQuery 導(dǎo)航插件和教程(下篇)
在下面的集合中,你會發(fā)現(xiàn)很多便利的 jQuery 導(dǎo)航插件和有用的教程,幫助你實(shí)現(xiàn)充滿吸引力的網(wǎng)站導(dǎo)航,讓你網(wǎng)站更有組織性和交互性2012-09-09