jQuery 中伙窃, $(document).ready()是什么意思?
頁面加載完成后样漆,瀏覽器會(huì)通過JavaScript給DOM元素添加事件为障。在原生的JavaScript中,用的是window.onload方法,而在jQuery中使用的是$(document).ready()方法放祟,$(document).ready()方法是事件模塊中最重要的一個(gè)函數(shù)鳍怨。通過使用這個(gè)方法,可以在DOM載入就緒時(shí)就對(duì)其進(jìn)行操縱并調(diào)用執(zhí)行它所綁定的函數(shù)跪妥,但這并不是說明跟這些元素關(guān)聯(lián)的文件都下載完畢了鞋喇。比如要對(duì)加載的圖片添加一些行為,例如點(diǎn)擊后圖片顯示或者隱藏眉撵,如果$(document).ready()方法進(jìn)行設(shè)置侦香,只要DOM元素加載完畢就可以操作了,不用等到所有圖片都下載完畢纽疟,但是使用window.onload操作罐韩,用戶必須等到所有圖片都下載完畢才可以操作。
$(document).ready()可以多次使用仰挣,比如
function a(){
console.log(a);
}
function b(){
console.log(b);
}
$(document).ready(function(){
a();
})
$(document).ready(function(){
b();
})
會(huì)依次輸出a 和b,但是使用window.onload的話伴逸,只會(huì)輸出后面那一個(gè),因?yàn)榘亚懊娴母采w了膘壶。
$(document).ready()方法也可以寫成:
1.
$(function(){
....
})
2.
$().ready(function(){
...
})
注意错蝴!
使用$(document).ready()方法時(shí),由于DOM準(zhǔn)備完畢就會(huì)被執(zhí)行颓芭,此時(shí)關(guān)聯(lián)的元素可能還沒加載完成顷锰,例如和圖片有關(guān)的html下載完畢,并且已經(jīng)解析為DOM樹了亡问,但可能圖片還未加載完畢官紫,所以此時(shí)圖片的高度寬度等屬性不一定有效肛宋,要解決這個(gè)方法可以用load()方法,這里不細(xì)講了束世。
$node.html()和$node.text()的區(qū)別?
$node.html()酝陈,無參數(shù)時(shí),用于獲取元素的HTML內(nèi)容(包括文本內(nèi)容和標(biāo)簽)毁涉,
$node.html(val),val為元素的HTML內(nèi)容沉帮,用于設(shè)置元素的HTML內(nèi)容。
$node.text(),無參數(shù)時(shí)贫堰,用于獲取元素的文本內(nèi)容穆壕。
$node.text(val),有參數(shù)時(shí),用于設(shè)置元素的文本內(nèi)容其屏。
<body>
<p>
<a href="">哈哈哈</a>
</p>
<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.js"></script>
<script>
var html=$("p").html();
console.log(html);
console.log($("p").text());
</script>
$.extend 的作用和用法?
$.extend是一個(gè)添加屬性方法的入口喇勋,
函數(shù)原型:$.extend([deep,] target [, object1 ] [, objectN ] )
用法:
1.當(dāng)我們提供兩個(gè)或多個(gè)對(duì)象給$.extend(),對(duì)象的所有屬性都添加到目標(biāo)對(duì)象(target參數(shù))偎行。
2.如果只有一個(gè)參數(shù)提供給$.extend()川背,這意味著目標(biāo)參數(shù)被省略。在這種情況下蛤袒,jQuery對(duì)象本身被默認(rèn)為目標(biāo)對(duì)象渗常。這樣,我們可以在jQuery的命名空間下添加新的功能汗盘。這對(duì)于插件開發(fā)者希望向 jQuery 中添加新函數(shù)時(shí)是很有用的。
目標(biāo)對(duì)象(第一個(gè)參數(shù))將被修改询一,并且將通過$.extend()返回隐孽,如果我們想保留原對(duì)象,我們可以將一個(gè)空對(duì)象作為目標(biāo)對(duì)象:如:var obj = $.extend({}, object1, object2);進(jìn)行對(duì)象屬性方法合并健蕊。
默認(rèn)情況下菱阵, $.extend()執(zhí)行的合并不會(huì)遞歸, 如果第一個(gè)對(duì)象的屬性本身是對(duì)象或數(shù)組缩功,則它將被第二個(gè)或后續(xù)對(duì)象中具有相同鍵的屬性完全覆蓋晴及。 這些值不合并,如果將 true作為該函數(shù)的第一個(gè)參數(shù)嫡锌,那么會(huì)在對(duì)象上進(jìn)行遞歸的合并虑稼。
用法:
1.$.extend()用來擴(kuò)展jQuery靜態(tài)方法
$.extend({
exFunc:function (){
console.log("hah");
}
});
$.exFunc();
2.將a1,a2…aN的每一項(xiàng)合并為obj的每一項(xiàng),并返回合并后的對(duì)象
var obj = {name:"xiaoming",age:20};
a1 = {name:"lihua",sex:"male"};
$.extend(obj,a1);
console.log(obj); //{name: "lihua", age: 20,sex:"male"}
3.想得到合并的結(jié)果势木,并不修改obj的結(jié)構(gòu)
var newObj = $.extend({},obj,a1,a2...aN);
//newObj就是得到的新對(duì)象
4.在jQuery對(duì)象擴(kuò)展一個(gè)命名空間
$.extend({nameScope:{}});
$.extend($.nameScope,{name:"tom"});
//將name添加到nameScope這個(gè)命名空間中
5.當(dāng)extend的第一參數(shù)為布爾值,決定extend是深拷貝還是淺拷貝蛛倦。
var src1 = {name:"tom",location:{city:"Beijing",county:"China"}};
var src2 = {name:"job",location:{live:"New York",county:"USA"}};
1.參數(shù)true,深拷貝
$.extend(true,src1,src2);
//合并后src1為:
{name: "job", location: {city: "Beijing",county: "USA",live: "New York"}}
里面的子元素也會(huì)進(jìn)行合并
2.參數(shù)為false啦桌,淺拷貝溯壶。
$.extend(false,src1,src2);
合并后src1為:
{name: "job", location: {live:"New York",county:"USA"}}
里面的子元素不會(huì)合并,直接覆蓋
參考:http://api.jquery.com/jQuery.extend/
jQuery 的鏈?zhǔn)秸{(diào)用是什么?
對(duì)發(fā)生在同一個(gè)jQuery對(duì)象上的一組動(dòng)作且改,可以直接連寫验烧,而無需重復(fù)獲取對(duì)象。如:
$("#myphoto").show().siblings().hide();
jQuery 中 data 函數(shù)的作用
在jQuery中又跛,可以通過data()方法將數(shù)據(jù)緩存碍拆,雖然使用全局變量或者局部變量可以將數(shù)據(jù)保存,但是變量不可以將數(shù)據(jù)緩存效扫,而且不依附于某元素自身倔监。如果使用data()方法可以針對(duì)元素定義數(shù)據(jù),在元素中存取數(shù)據(jù)菌仁,從而避免數(shù)據(jù)被循環(huán)使用的風(fēng)險(xiǎn)浩习,根據(jù)功能不同data有以下幾種使用格式:
1.根據(jù)元素中的名稱定義或者返回存儲(chǔ)的數(shù)據(jù),調(diào)用格式為:
data([name]);
其中name為可以選參數(shù)济丘,表示存儲(chǔ)數(shù)據(jù)的名稱谱秽。
2.根據(jù)元素中的名稱在元素上存儲(chǔ)或者設(shè)置數(shù)據(jù),調(diào)用格式為:
data(name,value);
其中name表示要存儲(chǔ)數(shù)據(jù)的名稱摹迷,value表示要存儲(chǔ)的數(shù)據(jù)疟赊。
比如:在一個(gè)p元素上設(shè)置或者保存數(shù)據(jù)
<body>
<p> </p>
<div class="divtip"></div>
<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.js"></script>
<script>
$(function(){
$("p").data("Data"); //初始值
$("p").data("Data","設(shè)置數(shù)據(jù)");
$(".divtip").append($("p").data("Data"));//顯示設(shè)置數(shù)據(jù)
})
</script>
</body
寫出以下功能對(duì)應(yīng)的 jQuery 方法:
給元素 $node 添加 class active,給元素 $noed 刪除 class active
$node.addClass("active");//添加
$noed.removeClass("active");//刪除
展示元素$node, 隱藏元素$node
$node.show();//展示
$node.hide();//隱藏
$node.css("display","block");//展示
$node.css("display","none");//隱藏
獲取元素$node 的 屬性: id峡碉、src近哟、title, 修改以上屬性
獲取屬性值:
$node.attr("id");
$node.attr("src");
$node.attr("title");
修改屬性:
$node.attr("id","val");
$node.attr("src","val");
$node.attr("title","val");
批量修改:
$node.attr({
"id":"val",
"src":"val",
"title":"val"
})
給$node 添加自定義屬性data-src
$node.attr("data-src","val");
在$ct 內(nèi)部最開頭添加元素$node
$ct.prepend($node);
或者:
$node.prependTo($ct);
在$ct 內(nèi)部最末尾添加元素$node
$ct.append($node);
或者:
$node.appendTo($ct);
刪除$node
$node.remove();//刪除后$node包含的所有后代都被刪除,刪除的是指向節(jié)點(diǎn)的引用鲫寄。
把$ct里內(nèi)容清空
$ct.empty();
在$ct 里設(shè)置 html <div class="btn"></div>
$ct.html("<div class="btn"></div>");
獲取吉执、設(shè)置$node 的寬度、高度(分別不包括內(nèi)邊距地来、包括內(nèi)邊距戳玫、包括邊框、包括外邊距)
p{
width: 100px;
height: 100px;
padding: 10px;
border: 1px solid;
margin: 10px;
}
<p></p>
不包括內(nèi)邊距:
$node.width();//100
$node,height();/100
包括內(nèi)邊距:
$node.innerWidth();//120
$node.innerHeight();//120
包括邊框:
$node.outerWidth();//122
$node.outerHeight();//122
包括外邊距:
$node.outerWidth(true);//142
$node.outerHeight(true);//142
獲取窗口滾動(dòng)條垂直滾動(dòng)距離
window.scrollTop();
獲取$node 到根節(jié)點(diǎn)水平未斑、垂直偏移距離
$node.offset();
修改$node 的樣式咕宿,字體顏色設(shè)置紅色,字體大小設(shè)置14px
$node.css({
"color":"red",
"font-size":"14px"
})
遍歷節(jié)點(diǎn)蜡秽,把每個(gè)節(jié)點(diǎn)里面的文本內(nèi)容重復(fù)一遍
$.each(function(index){
console.log($(this).text())
})
從$ct 里查找 class 為 .item的子元素
$ct.find(".item");
獲取$ct 里面的所有孩子
$ct.children();
對(duì)于$node府阀,向上找到 class 為'.ct'的父親,在從該父親找到'.panel'的孩子
$node.parents(".ct").find(".panel");
獲取選擇元素的數(shù)量
$node.length;
或者:
$node.size()
獲取當(dāng)前元素在兄弟中的排行
$node.index()
用jQuery實(shí)現(xiàn)以下操作:
當(dāng)點(diǎn)擊$btn 時(shí)载城,讓 $btn 的背景色變?yōu)榧t色再變?yōu)樗{(lán)色
<style>
.red {background: red; }
.blue{background: blue;}
</style>
$(function(){
$(".btn").on('click',function(){
$(".btn").addClass("red").toggleClass("blue")
})
})
當(dāng)窗口滾動(dòng)時(shí)肌似,獲取垂直滾動(dòng)距離
$(window).scroll(function(){
console.log($(window).scrollTop()+"px");
})
當(dāng)鼠標(biāo)放置到$div 上,把$div 背景色改為紅色诉瓦,移出鼠標(biāo)背景色變?yōu)榘咨?/p>
$(function(){
$div.on("mouseenter",function(){
$div.css("background","red");
});
$div.on("mouseleave",function(){
$div.css("background","blue");
})
});
當(dāng)鼠標(biāo)激活 input 輸入框時(shí)讓輸入框邊框變?yōu)樗{(lán)色川队,當(dāng)輸入框內(nèi)容改變時(shí)
把輸入框里的文字小寫變?yōu)榇髮懥ο福?dāng)輸入框失去焦點(diǎn)時(shí)去掉邊框藍(lán)色,控制臺(tái)展示輸入框里的文字
$(function(){
$('input').on("change",function(){
$(this).css("outline","blue");
if($(this).val().toLowerCase()){
$(this).on('keyup',function(){
var up= $(this).val().toUpperCase();
console.log(up);
});
}else {
console.log($(this).val());
}
});
});
當(dāng)選擇 select 后固额,獲取用戶選擇的內(nèi)容
<select name="" id="select">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
$("#select").on("change",function(){
console.log($("#select option:selected").text());
})
加載更多
router.js
app.get('/loadMore',function(req,res){
var index=req.query.page;
var len=req.query.length;
var data=[];
for(var i=0;i<len;i++){
data.push('新聞'+(parseInt(index)+i));
}
res.send({
status:0,
data:data
})
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
padding: 0;
margin: 0;
}
ul li {list-style: none}
a{
text-decoration: none;
color: #ff00ff;
}
.outer{
text-align: center;
width: 600px;
margin: 0 auto;
}
.wrap>li{
border: 1px solid #ddd;
text-align: center;
line-height: 2;
margin-bottom: 10px;
}
.wrap>li:hover{
background: #ddd;
}
#btn{
display: inline-block;
padding: 8px 20px ;
color: #fff;
background: #0000ff;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="outer">
<ul class="wrap">
</ul>
<a href="javascript:;" id="btn">加載更多</a>
</div>
</body>
<script src="js/jquery-1.8.3.min.js"></script>
<script>
var pageIndex=0;
$("#btn").on('click',function() {
$.ajax({
url: '/loadMore',
data: {
page: pageIndex,
length: 5
},
type: 'get',
dataType: 'json',
success: function (ret) {
pageIndex=pageIndex+5;
appendHtml(ret.data);
},
error: function () {
alert("獲取數(shù)據(jù)異常")
}
});
});
function appendHtml(ret){
var html='';
for(var i=0;i<ret.length;i++){
var i;
html+='<li>'+ret[i]+'</li>';
console.log(ret[i]);
}
// $.each(ret,function(){
// html+='<li>'+this+'</li>';
// console.log(this)
// });
$('.wrap').append(html);
}
2.或者這樣寫也可以
var pageIndex=0;
$("#btn").on('click',function() {
$.ajax({
url:'/loadMore',
method:'get',
data:{
page:pageIndex,
length:5
}
}).done(function(ret){
if(ret.status===0){
pageIndex=pageIndex+5;
appendHtml(ret.data);
}else{
alert("獲取數(shù)據(jù)異常")
}
}).fail(function(){
alert("系統(tǒng)異常")
})
});
function appendHtml(ret){
var html='';
for(var i=0;i<ret.length;i++){
var i;
html+='<li>'+ret[i]+'</li>';
console.log(ret[i]);
}
// $.each(ret,function(){
// html+='<li>'+this+'</li>';
// console.log(this)
// });
$('.wrap').append(html);
}
3.這樣更簡(jiǎn)單眠蚂,不過不是很清楚,還是前面的寫法好
$("#btn").on('click',function() {
$.get('/loadMore',{page:pageIndex, length:5}).done(function(ret){
if(ret.status===0){
pageIndex=pageIndex+5;
appendHtml(ret.data);
}else{
alert("獲取數(shù)據(jù)異常")
}
}).fail(function(){
alert("系統(tǒng)異常")
})
});
function appendHtml(ret){
var html='';
for(var i=0;i<ret.length;i++){
var i;
html+='<li>'+ret[i]+'</li>';
console.log(ret[i]);
}
// $.each(ret,function(){
// html+='<li>'+this+'</li>';
// console.log(this)
// });
$('.wrap').append(html);
}
</script>
結(jié)果:
發(fā)現(xiàn)用for循環(huán)和$.each如果都寫this的話斗躏,獲取到的值是不一樣的逝慧,for循環(huán)獲取到的是window對(duì)象,結(jié)果發(fā)現(xiàn)是作用域的問題啄糙,但是不知道為何$,each的this指的是返回?cái)?shù)組里面的值笛臣。