jQuery 常見小例匯總
1
//這段代碼展示了在用戶未輸入值時,
//如何在文本類型的input域中保留
//一個默認(rèn)值
wap_val = [];
$(".swap").each(function(i){
wap_val[i] = $(this).val();
$(this).focusin(function(){
if ($(this).val() == swap_val[i]) {
$(this).val("");
}
}).focusout(function(){
if ($.trim($(this).val()) == "") {
$(this).val(swap_val[i]);
}});});
2
var el = $('#id');
el.html(el.html().replace(/word/ig, ''));
3
$('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");
});
});
//現(xiàn)在用
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});
4.如何把已創(chuàng)建的元素動態(tài)地添加到DOM中:
var newDiv = $('');
newDiv.attr('id','myNewDiv').appendTo('body');
5
var cloned = $('#somediv').clone();
6
if($(element).is(':visible') == 'true') {
//該元素是可見的
}
7.JQ中定位
jQuery.fn.center = function () {
this.css('position','absolute');
this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollTop() + 'px');
this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');
return this;
}
//這樣來使用上面的函數(shù):
$(element).center();
8.如何把有著某個特定名稱的所有元素的值都放到一個數(shù)組中:
var arrInputValues = new Array();
$("input[name='table[]']").each(function(){
arrInputValues.push($(this).val());
});
9.在jQuery中如何使用.siblings()來選擇同輩元素
$('#nav li').click(function(){
$('#nav li').removeClass('active');
$(this).addClass('active');
});
//替代做法是
$('#nav li').click(function(){
$(this).addClass('active').siblings().removeClass('active');
});
10.正反選
var tog = false;
$('a').click(function() {
$("input[type=checkbox]").attr("checked",!tog);
tog = !tog;
});
11.如何獲得鼠標(biāo)墊光標(biāo)位置x和y
$(document).ready(function() {
$(document).mousemove(function(e){
$('#XY').html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY);
});
});
12.如何把整個的列表元素(List Element,LI)變成可點擊的
$("ul li").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
13.如何檢查圖像是否已經(jīng)被完全加載進來
$('#theImage').attr('src', 'image.jpg').load(function() {
alert('This Image Has Been Loaded');
});
14.如何檢查cookie是否啟用
var dt = new Date();
dt.setSeconds(dt.getSeconds() + 60);
document.cookie = "cookietest=1; expires=" + dt.toGMTString();
var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
if(!cookiesEnabled) {
//沒有啟用cookie
}
15.如何讓cookie過期:
var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
Jquery的autocomplete插件用法及參數(shù)講解
今天小編就為大家分享一篇關(guān)于Jquery的autocomplete插件用法及參數(shù)講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
jQuery 順便學(xué)習(xí)下CSS選擇器 奇偶匹配nth-child(even)
今天學(xué)習(xí)jQuery,看到nth-child(even)用法,特意找了下這個選擇器的用法,在CSS3標(biāo)準(zhǔn)中,用法很強大。2010-05-05

