0. 如何建立嵌套的過濾器: css
1
2
3
4
5
|
//容許你減小集合中的匹配元素的過濾器,
//只剩下那些與給定的選擇器匹配的部分。在這種狀況下,
//查詢刪除了任何沒(:not)有(:has)
//包含class爲「selected」(.selected)的子節點。
.filter(":not(:has(.selected))")
|
1
2
3
4
5
6
7
8
9
10
|
varallItems = $("div.item");
varkeepList = $("div#container1 div.item");
//如今你能夠繼續使用這些jQuery對象來工做了。例如,
//基於複選框裁剪「keep list」,複選框的名稱
//符合
< DIV >class names:
$(formToLookAt +" input:checked").each(function() {
keepList = keepList.filter("."+ $(this).attr("name"));
});
< /DIV>
|
2. 任何使用has()來檢查某個元素是否包含某個類或是元素: 數組
1
2
3
4
|
//jQuery 1.4.*包含了對這一has方法的支持。該方法找出
//某個元素是否包含了其餘另外一個元素類或是其餘任何的
//你正在查找並要在其之上進行操做的東東。
$("input").has(".email").addClass("email_icon");
|
3. 如何使用jQuery來切換樣式表 瀏覽器
1
2
|
//找出你但願切換的媒體類型(media-type),而後把href設置成新的樣式表。
$('link[media='screen']').attr('href','Alternative.css');
|
4. 如何限制選擇範圍(基於優化目的): cookie
1
2
3
4
5
6
|
//儘量使用標籤名來做爲類名的前綴,
//這樣jQuery就不須要花費更多的時間來搜索
//你想要的元素。還要記住的一點是,
//針對於你的頁面上的元素的操做越具體化,
//就越能下降執行和搜索的時間。
varin_stock = $('#shopping_cart_items input.is_in_stock');
|
1
2
3
4
5
|
<ulid="shopping_cart_items">
<li><inputtype="radio"value="Item-X"name="item"class="is_in_stock"/> Item X</li>
<li><inputtype="radio"value="Item-Y"name="item"class="3-5_days"/> Item Y</li>
<li><inputtype="radio"value="Item-Z"name="item"class="unknown"/> Item Z</li>
</ul>
|
5. 如何正確地使用ToggleClass: app
1
2
3
4
5
6
|
//切換(toggle)類容許你根據某個類的
//是否存在來添加或是刪除該類。
//這種狀況下有些開發者使用:
a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton');
//toggleClass容許你使用下面的語句來很容易地作到這一點
a.toggleClass('blueButton');
|
6. 如何設置IE特有的功能: ide
1
2
3
|
if($.browser.msie) {
// Internet Explorer就是個虐待狂
}
|
7. 如何使用jQuery來代替一個元素: 函數
1
|
$('#thatdiv').replaceWith('fnuh');
|
8. 如何驗證某個元素是否爲空: 測試
1
2
3
|
if($('#keks').html() ==null) {
//什麼都沒有找到;
}
|
9. 如何從一個未排序的集合中找出某個元素的索引號 優化
1
2
3
|
$("ul > li").click(function() {
varindex = $(this).prevAll().length;
});
|
10. 如何把函數綁定到事件上:
1
2
3
|
$('#foo').bind('click',function() {
alert('User clicked on "foo."');
});
|
11. 如何追加或是添加html到元素中:
1
|
$('#lal').append('sometext');
|
12. 在建立元素時,如何使用對象字面量(literal)來定義屬性
1
|
vare = $("", { href:"#", class:"a-class another-class", title:"..."});
|
13. 如何使用多個屬性來進行過濾
1
2
3
|
//在使用許多相相似的有着不一樣類型的input元素時,
//這種基於精確度的方法頗有用
varelements = $('#someid input[type=sometype][value=somevalue]').get();
|
14. 如何使用jQuery來預加載圖像:
1
2
3
4
5
6
7
|
jQuery.preloadImages =function() {
for(vari = 0; i < arguments.length; i++) {
$("<img />").attr('src', arguments[i]);
}
};
//用法
$.preloadImages('image1.gif','/path/to/image2.png','some/image3.jpg');
|
15. 如何爲任何與選擇器相匹配的元素設置事件處理程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
$('button.someClass').live('click', someFunction);
//注意,在jQuery 1.4.2中,delegate和undelegate選項
//被引入代替live,由於它們提供了更好的上下文支持
//例如,就table來講,之前你會用
//.live()
$("table").each(function(){
$("td",this).live("hover",function(){
$(this).toggleClass("hover");
});
});
//如今用
$("table").delegate("td","hover",function(){
$(this).toggleClass("hover");
});
|
16. 如何找到一個已經被選中的option元素:
1
|
$('#someElement').find('option:selected');
|
17. 如何隱藏一個包含了某個值文本的元素:
1
|
$("p.value:contains('thetextvalue')").hide();
|
18. 如何自動滾動到頁面中的某區域
1
2
3
4
5
6
7
8
|
jQuery.fn.autoscroll =function(selector) {
$('html,body').animate(
{scrollTop: $(selector).offset().top},
500
};
}
//而後像這樣來滾動到你但願去到的class/area上。
$('.area_name').autoscroll();
|
19. 如何檢測各類瀏覽器:
1
2
3
4
|
檢測Safari (if( $.browser.safari)),
檢測IE6及以後版本 (if($.browser.msie && $.browser.version > 6 )),
檢測IE6及以前版本 (if($.browser.msie && $.browser.version <= 6 )),
檢測FireFox 2及以後版本 (if($.browser.mozilla && $.browser.version >='1.8'))
|
20. 如何替換串中的詞
1
2
|
varel = $('#id');
el.html(el.html().replace(/word/ig,''));
|
1
2
3
|
$(document).bind('contextmenu',function(e){
returnfalse;
});
|
22. 如何定義一個定製的選擇器
1
2
3
4
5
6
7
8
9
|
$.expr[':'].mycustomselector =function(element, index, meta, stack){
// element- 一個DOM元素
// index – 棧中的當前循環索引
// meta – 有關選擇器的元數據
// stack – 要循環的全部元素的棧
// 若是包含了當前元素就返回true
// 若是不包含當前元素就返回false };
// 定製選擇器的用法:
$('.someClasses:test').doSomething();
|
23. 如何檢查某個元素是否存在
1
2
3
|
if($('#someDiv').length) {
//萬歲!!!它存在……
}
|
24. 如何使用jQuery來檢測右鍵和左鍵的鼠標單擊兩種狀況:
1
2
3
4
5
6
7
|
$("#someelement").live('click',function(e) {
if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
alert("Left Mouse Button Clicked");
}elseif(e.button == 2) {
alert("Right Mouse Button Clicked");
}
});
|
25. 如何顯示或是刪除input域中的默認值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//這段代碼展現了在用戶未輸入值時,
//如何在文本類型的input域中保留
//一個默認值
wap_val = [];
$(".swap").each(function(i){
wap_val[i] = $(this).val();
$(this).focusin(function(){
if($(this).val() == wap_val[i]) {
$(this).val("");
}
}).focusout(function(){
if($.trim($(this).val()) =="") {
$(this).val(wap_val[i]);
}
});
});
|
1
|
<input type="text"value="Enter Username here.."class="swap"/>
|
26. 如何在一段時間以後自動隱藏或關閉元素(支持1.4版本):
1
2
3
4
5
6
|
//這是1.3.2中咱們使用setTimeout來實現的方式
setTimeout(function() {
$('.mydiv').hide('blind', {}, 500)
}, 5000);
//而這是在1.4中可使用delay()這一功能來實現的方式(這很像是休眠)
$(".mydiv").delay(5000).hide('blind', {}, 500);
|
27. 如何把已建立的元素動態地添加到DOM中:
1
2
|
varnewDiv = $('');
newDiv.attr('id','myNewDiv').appendTo('body');
|
28. 如何限制「Text-Area」域中的字符的個數:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
jQuery.fn.maxLength =function(max){
this.each(function(){
vartype =this.tagName.toLowerCase();
varinputType =this.type?this.type.toLowerCase() :null;
if(type =="input"&& inputType =="text"|| inputType =="password"){
//Apply the standard maxLength
this.maxLength = max;
}
elseif(type =="textarea"){
this.onkeypress =function(e){
varob = e || event;
varkeyCode = ob.keyCode;
varhasSelection = document.selection? document.selection.createRange().text.length > 0 :this.selectionStart !=this.selectionEnd;
return!(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
};
this.onkeyup =function(){
if(this.value.length > max){
this.value =this.value.substring(0,max);
}
};
}
});
};
//用法
$('#mytextarea').maxLength(500);
|
29. 如何爲函數建立一個基本的測試
1
2
3
4
5
6
7
8
9
|
//把測試單獨放在模塊中
module("Module B");
test("some other test",function() {
//指明測試內部預期有多少要運行的斷言
expect(2);
//一個比較斷言,至關於JUnit的assertEquals
equals(true,false,"failing test");
equals(true,true,"passing test");
});
|
30. 如何在jQuery中克隆一個元素:
1
|
varcloned = $('#somediv').clone();
|
31. 在jQuery中如何測試某個元素是否可見
1
2
3
|
if($(element).is(':visible') =='true') {
//該元素是可見的
}
|
32. 如何把一個元素放在屏幕的中心位置:
1
2
3
4
5
6
7
8
|
jQuery.fn.center =function() {
this.css('position','absolute');
this.css('top', ( $(window).height() -this.height() ) / 2 +$(window).scrollTop() +'px');
this.css('left', ( $(window).width() -this.width() ) / 2 +$(window).scrollLeft() +'px');
returnthis;
}
//這樣來使用上面的函數:
$(element).center();
|
33. 如何把有着某個特定名稱的全部元素的值都放到一個數組中:
1
2
3
4
|
vararrInputValues =newArray();
$("input[name='table[]']").each(function(){
arrInputValues.push($(this).val());
});
|
34. 如何從元素中除去html
1
2
3
4
5
6
7
8
9
10
11
|
(function($) {
$.fn.stripHtml =function() {
varregexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
this.each(function() {
$(this).html( $(this).html().replace(regexp,」") );
});
return$(this);
}
})(jQuery);
//用法:
$('p').stripHtml();
|
35. 如何使用closest來取得父元素:
1
|
$('#searchBox').closest('div');
|
36. 如何使用Firebug和Firefox來記錄jQuery事件日誌:
1
2
3
4
5
6
7
8
9
|
// 容許鏈式日誌記錄
// 用法:
$('#someDiv').hide().log('div hidden').addClass('someClass');
jQuery.log = jQuery.fn.log =function(msg) {
if(console){
console.log("%s: %o", msg,this);
}
returnthis;
};
|
37. 如何強制在彈出窗口中打開連接:
1
2
3
4
5
6
7
|
jQuery('a.popup').live('click',function(){
newwindow=window.open($(this).attr('href'),'','height=200,width=150');
if(window.focus) {
newwindow.focus();
}
returnfalse;
});
|
38. 如何強制在新的選項卡中打開連接:
1
2
3
4
5
|
jQuery('a.newTab').live('click',function(){
newwindow=window.open($(this).href);
jQuery(this).target ="_blank";
returnfalse;
});
|
39. 在jQuery中如何使用.siblings()來選擇同輩元素
1
2
3
4
5
6
7
8
9
|
// 不這樣作
$('#nav li').click(function(){
$('#nav li').removeClass('active');
$(this).addClass('active');
});
//替代作法是
$('#nav li').click(function(){
$(this).addClass('active').siblings().removeClass('active');
});
|
40. 如何切換頁面上的全部複選框:
1
2
3
4
5
6
|
vartog =false;
// 或者爲true,若是它們在加載時爲被選中狀態的話
$('a').click(function() {
$("input[type=checkbox]").attr("checked",!tog);
tog = !tog;
});
|
41. 如何基於一些輸入文原本過濾一個元素列表:
1
2
3
4
5
|
//若是元素的值和輸入的文本相匹配的話
//該元素將被返回
$('.someClass').filter(function() {
return$(this).attr('value') == $('input#someId').val();
})
|
42. 如何得到鼠標墊光標位置x和y
1
2
3
4
5
|
$(document).ready(function() {
$(document).mousemove(function(e){
$(’#XY’).html(」X Axis : 」 + e.pageX + 」 | Y Axis 」 + e.pageY);
});
});
|
43. 如何把整個的列表元素(List Element,LI)變成可點擊的
1
2
3
4
|
$("ul li").click(function(){
window.location=$(this).find("a").attr("href");
returnfalse;
});
|
1
2
3
4
5
6
|
<ul>
<li><ahref="#">Link 1</a></li>
<li><ahref="#">Link 2</a></li>
<li><ahref="#">Link 3</a></li>
<li><ahref="#">Link 4</a></li>
</ul>
|
44. 如何使用jQuery來解析XML(基本的例子):
1
2
3
4
5
6
|
functionparseXml(xml) {
//找到每一個Tutorial並打印出author
$(xml).find("Tutorial").each(function() {
$("#output").append($(this).attr("author") +"");
});
}
|
45. 如何檢查圖像是否已經被徹底加載進來
1
2
3
|
$('#theImage').attr('src','image.jpg').load(function() {
alert('This Image Has Been Loaded');
});
|
46. 如何使用jQuery來爲事件指定命名空間:
1
2
3
4
5
6
|
//事件能夠這樣綁定命名空間
$('input').bind('blur.validation',function(e){
// ...
});
//data方法也接受命名空間
$('input').data('validation.isValid',true);
|
47. 如何檢查cookie是否啓用
1
2
3
4
5
6
7
|
vardt =newDate();
dt.setSeconds(dt.getSeconds() + 60);
document.cookie ="cookietest=1; expires="+ dt.toGMTString();
varcookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
if(!cookiesEnabled) {
//沒有啓用cookie
}
|
48. 如何讓cookie過時:
1
2
3
|
vardate =newDate();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie('example','foo', { expires: date });
|
49. 如何使用一個可點擊的連接來替換頁面中任何的URL
1
2
3
4
5
6
7
8
9
10
11
|
$.fn.replaceUrl =function() {
varregexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
this.each(function() {
$(this).html(
$(this).html().replace(regexp,'<a href="$1">$1</a>‘)
);
});
return $(this);
}
//用法
$('p').replaceUrl();
|