1.$(document).ready() 方法 可以簡(jiǎn)寫(xiě)成$(function(){});
1.這個(gè)函數(shù)中的代碼只會(huì)在我們的頁(yè)面加載時(shí)候運(yùn)行一次稚虎,確保執(zhí)行js之前頁(yè)面所有的dom已經(jīng)準(zhǔn)備就緒
2.點(diǎn)擊"Get Message"按鈕,將class為message 的元素的文本改為:“Here is the message”
<script>
$(document).ready(function() {
$("#getMessage").on("click", function(){
// Only change code below this line.
$(".message").html("Here is the message");
// Only change code above this line.
});
});
</script>
<div class="container-fluid">
<div class = "row text-center">
<h2>Cat Photo Finder</h2>
</div>
<div class = "row text-center">
<div class = "col-xs-12 well message">
The message will go here
</div>
</div>
<div class = "row text-center">
<div class = "col-xs-12">
<button id = "getMessage" class = "btn btn-primary">
Get Message
</button>
</div>
</div>
</div>
2.Ajax網(wǎng)絡(luò)請(qǐng)求
1.你的Ajax函數(shù)將把文字"The message will go here"替換成此從FreeCodeCam的貓圖API中獲得的原始JSON數(shù)據(jù)锄贷。
<script>
$(document).ready(function() {
$("#getMessage").on("click", function(){
// Only change code below this line.
$.getJSON("/json/cats.json", function(json) {
$(".message").html(JSON.stringify(json));
});
// Only change code above this line.
});
});
</script>
2.將獲取到的數(shù)據(jù)渲染到頁(yè)面上
<script>
$(document).ready(function() {
$("#getMessage").on("click", function() {
?? $.getJSON("/json/cats.json", function(json) {
var html = "";
// Only change code below this line.
json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'cat'>";
keys.forEach(function(key){
html += "<b>" + key + "</b>:" + val[key] + "</br>";
});
html+="</div><br>";
});
console.log(html);
// Only change code above this line.
???? $(".message").html(html);
?? });
});
});
</script>
3.理解jquery的$.extend()缚窿、$.fn和$.fn.extend()
雖然 javascript沒(méi)有明確的類(lèi)的概念番电,但是可以構(gòu)建類(lèi)似類(lèi)的定義乍恐。
jQuery便是一個(gè)封裝得非常好的類(lèi),比如母剥,$("#btn1") 會(huì)生成一個(gè) jQuery類(lèi)的實(shí)例滞诺,理解這一點(diǎn)很重要。
$.extend() = jquery.extention 為jQuery類(lèi)添加類(lèi)方法环疼,可以理解為添加靜態(tài)方法习霹。如
jQuery.extend({
min: function(a, b) { return a < b ? a : b; },
max: function(a, b) { return a > b ? a : b; }
});
jQuery.min(2,3); // 2
jQuery.max(4,5); // 5
$.fn是指jQuery的命名空間,fn上的成員(方法function及屬性property)炫隶,會(huì)對(duì)jQuery實(shí)例每一個(gè)有效淋叶。
查看jQuery代碼,就不難發(fā)現(xiàn)伪阶。
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {//....
};
jQuery.fn.extend(object)對(duì)jQuery.prototype進(jìn)得擴(kuò)展煞檩,就是為jQuery類(lèi)添加“成員函數(shù)”。jQuery類(lèi)的實(shí)例可以使用這個(gè)“成員函數(shù)
$.fn.extend({
alertWhileClick:function() {
$(this).click(function(){
alert($(this).val());
});
}
});
$("#input1").alertWhileClick(); // 頁(yè)面上為: