//鼠標點擊後執行 <p id="" class="" onclick="console.log(2)">onclick</p>
<script type='text/javascript'></script>
<script type='text/javascript' src='js文件路徑'></script>
console.log('hello world'); //window.log+tab,window是全局對象 alert('hello world'); var weather = prompt(message:'請輸入今每天氣');
var a = 2; //num var b = '2' + a; // string var c = true; // boolean console.log(typeof(a)); var e; //先聲明後定義 console.log(e); //值和類型都是undifined var f = null; console.log(f) // 類型是undefiend,數值爲null console.log(typeof(f)) //空對象
// str轉num var s = '123'; new_s = Number(s);
var num = 123; new_s = num.toString();
//Array var arr = ['henry' 'echo' 'dean']; // 修改元素 arr[2] = 'diane'; arr.length;
//Object,定義在對象中的函數,即對象的方法 var obj = {name:'echo', age:19, fav:function(){ console.log(this) }}; obj.fav()
//function,定義在對象中的函數即對象的方法,{}表示做用域,也是對象 function add(形參1, 形參2){ var c = 2; return a+b; }; console.log(add{2, 5});
var add = function() { };
(function(){})();
//遞增、遞減 var a = 1; a += 1; a++; console.log(a); // a++ 的迷惑 var a = 4; //先賦值後++ var c = a++; console.log(c); console.log(a); // ++a 的迷惑 var a = 4; //先++後賦值 var c = ++a; console.log(c); console.log(a);
var name = 'henry', age = 19; var str = name + '今年是' + age + '歲'; //es6的模版string,必須是反引號 var str = `${name}今年${age}歲`;
var arr = [1, 2, 'henry']; // 索引取值 arr[0]; // 遍歷 // 預解釋,變量提高 // var c=2; for (var i = 0; i < arr.length; i++){ console.log(arr[i]); }
arr[2][2]; //取到第二行,第二列
&&; ||; !;
var score = 70; if (score > 80){ console.log('play'); }else if(score > 60){ console.log('stay at home'); }else{ console.log('study'); };
var weather = prompt('weather'); switch(weather){ case 'nice': console.log('nice'); break; case 'rain': console.log('rain'); break; default: console.log('bye') break; }
// true var a = 1 == '1'; // false var a = 1 == 2; var a = 1 == '1';
// for循環 arr = [8, 9, 0] for (var i = 0; i < arr.length; i++){ } // while循環 var a = 1; while (a < 100){ console.log(a); a++; } // do...while do{ }while(a < 100);
// function也會有變量提高現象 function fun(){ console.log(arguments); switch(arguments.length){ case 2: console.log(2); break; case 3: console.log(3); break; default:break; } } fun(1, 2); fun(3, 4, 5);
new Object(); new Array(); new String(); new Number();
var Person = { name:'henry', age:19, fav:function(){ console.log(this); } }; Person.fav(); console.log(Person.name); console.log(Person.age);
var obj = {}; obj.name = 'henry'; console.log(obj.name) obj.fav = function(){ console.log(this); // this 指向obj對象 }; obj.fav(); console.log(this); // this window
var obj = {name:'echo'}; var name = 'henry'; function add(x, y){ this.x = x; this.y = y; console.log(this.name); console.log(this); console.log(x); console.log(y); }; add(); // 不能夠改變this指向 add.call(obj, 1, 2); // 能夠改變this指向 add.apply(null, [1, 2]); // 能夠改變this指向 console.dir(add);
function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function () { return '(' + this.x + ', ' + this.y + ')'; }; var p = new Point(1, 2);
var obj = new Array(); console.log(obj);
var = arr['red', 'yellow', 'green'];
// if 內只有一行代碼是能夠省略大括號 if (Array.isArray(arr)) console.log('true');
var arr = ['red', 'green'] Array.isArray(arr); // 判斷arr是不是數組,返回true則是 arr.toString(); // 把數組中內容取出,用逗號拼接 num = 123; num.toString(); // 數字轉字符串 arr.join('||'); // 以||拼接
push() pop() var val = arr.pop(); // 返回刪除的內容 console.log(val); // val是pop的返回值 console.log(arr); console.log(arr.push('xixixi'));; // 返回值爲res,最新數組長度 console.log(arr);
shift() unshift() var val = arr.unshift('heiheihei', 'hahaha');// 往數組的前面填充內容 console.log(arr); console.log(val); // 返回數組最新長度 console.log(arr.shift()); // 刪除第一個
var names = ['henry', 'echo', 'dean']; var val = names.splice(1, 0, 'diane'); // 在索引1位置添加 console.log(names); console.log(val); names.splice(1, 1); // 從索引1位置刪除1個值 names.splice(1, 1, 'xixixi'); // 從索引1位置替換1個
var num = [5, 2, 3]; num.reverse();
// 會轉換成字符串進行比較 a = [2,1,13,4,56,6, 'henry']; console.log(a.sort()); // [1, 13, 2, 4, 56, 6, "henry"]
// 數組拼接,並不改變原來值 var new_num = num.concat(1, 2, 3);
// 不會更改初始值 num = [1,2,3,4,5,4,3,2,1] num.slice(5) // 索引5以後的全部值 num.slice(5,7) // 索引5-7 不包擴7 num.slice(-3,-1) // 倒數第三個到倒數第一個 num.slice(-3,-4) // 取不到值
num = [1,2,3,4,5,4,3,2,1] var a = num.indexOf(4); // 3 var a = num.lastIndexOf(4); // 5
// 回調函數 arr.forEach(function(item, index){ console.log(index); console.log(item); }); function fn(){ console.log(arguments); // arguments不是數組,僞數組 for (var i = 0; i < arguments.length; i++){ console.log(arguments[i]); } } fn(2,3,4); fn.length; // 形參個數
s = 'henry'; console.log(s.length);
console.log(s.charAt(2));
console.log(s.charCodeAt(2));
console.log(s.concat('&echo'));
s = 'henry&echo'; s.slice(3,7);
s = 'henry&echo'; s.substring(3,7);
s = 'henry&echo'; s.substr(3,7);
s = 'henry&echo'; s.indexof('o'); // 數據類型要一致
s = 'henry&echo'; s.lastIndexOf('o'); // 數據類型要一致
s = ' he nry '; s.trim(); s.trimLeft(); s.trimRight(); s.trimEnd();
s = 'henry'; s.toLowerCase(); s.toUpperCase();
var time = new Date();
time.getDate(); // 返回日期對象的第幾天
time.getMonth(); // 返回月份,須要 + 1
time.getFullYear();
time.getDay();
time.getHours();
time.getMinutes();
time.getSeconds();
1.time.toString(); // Sun Jun 09 2019 17:13:35 GMT+0800 (CST) 2.time.toLocaleString(); //6/9/2019, 5:13:35 PM 3.time.toDateString(); // "Sun Jun 09 2019" 4.time.toLocaleDateString(); // "6/9/2019" 5.time.toTimeString() // "17:27:04 GMT+0800 (CST)" 6.time.toLocaleTimeString() // "5:27:04 PM" 7.time.toGMTString(); // "Sun, 09 Jun 2019 09:27:04 GMT"
var time = new Date(); console.log(time); console.log(time.getDate()); console.log(time.getFullYear()); console.log(time.getMonth()+1); console.log(time.getDay()); console.log(time.getHours()); console.log(time.getMinutes()); console.log(time.getSeconds()); console.log(time.toLocaleString()); //2019/6/3 下午11:50:36 var weeks = ['星期天','星期一','星期二','星期三','星期四','星期五','星期六']; console.log(weeks[date.getDay()]); var day = weeks[date.getDay()]; document.write(`<a href="#">${day}</a>`) var a = 1 < 2 ? "yes": "no"; console.log(a);
var a = 1 > 2 ? 'yes': 'no';
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2 id="time"></h2> <script> var timeObj = document.getElementById('time'); console.log(time); function getNowTime() { var time = new Date(); var hour = time.getHours(); var minute = time.getMinutes(); var second = time.getSeconds(); var temp = "" + ((hour > 12) ? hour - 12 : hour); if (hour == 0) { temp = "12"; } temp += ((minute < 10) ? ":0" : ":") + minute; temp += ((second < 10) ? ":0" : ":") + second; temp += (hour >= 12) ? " P.M." : " A.M."; timeObj.innerText = temp; } setInterval(getNowTime, 20); </script> </body> </html>
var s = '123'; parseInt(s); // 若是s中包含非數字,則只保留其數字部分,第一個字符爲非數字則會報NaN
var s = '123.123'; parseFloat(s);
var c = 6/0; // 會出現infinity
Number('123d'); // NaN: not a number Number('123');
String(123);
var a = 2; a = a + ''; // 或者 a.toString();
arr = [1,2,3,4,5] var max = Math.max.apply(null, arr);
var num = 25.7; var num2 = 25.2; alert(Math.ceil(num)); //26 alert(Math.floor(num)); //25 alert(Math.round(num)); //26 alert(Math.round(num2)); //25
function random(lower, upper) { return Math.floor(Math.random() * (upper - lower)) + lower; }
var url = 'https://www.bai du.com'; var a1 = encodeURI(url); var a2 = encodeURIComponent(url); console.log(a1); console.log(a2); console.log(decodeURI(a1)); console.log(decodeURIComponent(a2)) // 使用 encodeURI()編碼後的結果是除了空格以外的其餘字符都原封不動,只有空格被替換成了 %20。 // 而 encodeURIComponent()方法則會使用對應的編碼替換全部非字母數字字符
var color = "red"; function sayColor(){ alert(window.color); } window.sayColor(); // red
// 獲取0-256之間的隨機數 function random(min, max){ return min + Math.floor(Math.random() * max); } function randomColor(){ var r = random(0, 256), g = random(0, 256), b = random(0, 256); return `rag(${r},${g},${b} )`; } var color = randomColor(); console.log(color);
function creationCode(){ var code = ''; var code_l = 4; var s_code = Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R', 'S','T','U','V','W','X','Y','Z'); for (var i = 0; i < code_l; i++){ s = s_code[random(0,37)] code += s; } return code; } var code = creationCode(); console.log(code);
var a = window.alert('肯定離開了');
// 有返回值,肯定爲true或取消爲false var a = window.confirm('肯定刪除?');
var a = window.promopt('今每天氣怎麼樣?')
// 延時2秒,異步、非阻塞 var i = 0; timer = setTimeout(function(){ console.log('hello world'); }, 2000); // 清除定時器 clearTimeout(timer); timer = setTimeout(function(){ console.log('test your speed'); }, 2000); console.log('看看阻不阻塞')
var i = 0; timer = setInterval(function(){ i++; console.log(i); if (i === 10){ // 清除定時器 clearInterval(timer); } }, 1000);
console.log(window.location); console.log(window.location.host); console.log(window.location.hostname); console.log(window.location.herf); console.log(window.location.origin); console.log(window.location.port); // console.log(window.location.reload()); reload: f reload(); // 方法 location.reload();
// 刷新 setInterval(function(){ // 通常用於測試 // ajax用於局部刷新 locatoin.reload(); }, 2000);
var box = document.getElementById('box'); console.log(box); console.dir(box); // 查看box全部屬性和方法
var box = document.getElementsByTagName('div'); // 使用拍它思想,操做標籤,點擊任意一個改變樣式,即改變類名 var li = document.getElementsByTagName('li'); for (var i = 0; i < li.length; i++){ // console.log(li[i]); // 這裏的this指向當前對象 this.onclick = function(){ for (var j = 0; j < li.length; j++){ this.className = ''; } this.className='active-li'; };
var lis = document.getElementsByClassName('active'); // 經過id獲取時, var box = document.getElementById('box'); console.log(box.children);
// 當前文檔啊 console.log(document); // html中的body console.log(document.body); // html console.log(document.documentElement);
// 屬性所有使用駝峯式 box.style.color box.style.backgroudColor
var box = window.document.getElementById('box'); console.log(box); // 綁定事件 box.onmouseover = function(){ this.style.backgroundColor = 'red'; } box.onmouseout = function(){ this.style.backgroundColor = 'yellowgreen'; }
var isRed = true; // 綁定事件 box.onclick = function(){ if (isRed){ this.style.backgroundColor = 'yellow'; isRed = false; }else{ this.style.backgroundColor = 'red'; isRed = true; } } // 設置週期定時, 此時不能用this,由於this指向window setInterval (function(){ if (isRed){ box.style.backgroundColor = 'yellow'; isRed = false; }else{ box.style.backgroundColor = 'red'; isRed = true;} },1000);
var p = window.document.getElementById('p1'); console.dir(p); p.className += ' b'; // 會覆蓋以前的類 p.className = 'b';
setAttribute(name, value); getAttribute(name); var p = document.getElementById('p1'); p.setAttribute('class', 'active'); // 自定義屬性設置,只能在節點對象上 p.setAttribute('self', 'active'); // 不會顯示到頁面中的elements中 p.self = '123'; p.class; p.title;
var p = window.document.getElementById('p1'); console.dir(p); // p.className += ' b'; // p.className = 'b'; p.self = '123'; // p.setAttribute('self', 'active'); isTrue = true; p.onmouseover = function(){ if (isTrue){ this.className += ' b'; isTrue = false; }else{ this.className = 'a'; isTrue = true; } }
var ul = document.getElementById('box'); // 建立節點 var li1 = document.createElement('li'); var li2 = document.createElement('li'); // 只設置文本 li1.innerText = '123'; // 設置li中的html內容 li1.innerHTML = '<a herf = ''>123</a>'; // 設置類名 l1i.setAttribute('class', 'active'); // 設置樣式 li1.children[0].style.color = 'red'; li1.children[0].style.fontSize = 20px; // 追加節點 ul.appendChild(li1); // 在li1前插入li2 ul.insertBefore(li2, li1); // 刪除節點 ul.removeChild(li1);
var box = document.getElementById('box'); // 建立節點對象 var li1 = document.createElement('li'); var li2 = document.createElement('li'); // 設置節點內容和屬性(2中設置內容方式) li1.innerText = '123'; li1.innerHTML = "<a href=''>456</a>"; li1.setAttribute('class', 'active') // 添加節點到父節點 box.appendChild(li1); box.insertBefore(li2, li1); // 刪除孩子節點li1 box.removeChild(li1);
var data = [ {id:1, name:'henry', age:19}, {id:2, name:'echo', age:18}, {id:3, name:'dean', age:28}, {id:4, name:'oleg', age:26}, {id:5, name:'diane', age:27} ] for (var i = 0; i < data.length; i++){ console.log(data[i].name); var li = document.createElement('li'); li.innerHTML = `<p>${data[i].id}</p> <p>${data[i].name}</p><p>${data[i].age}</p>`; box.appendChild(li) }
var box = document.getElementById('imgBox'); var prev = document.getElementById('prev'); var next = document.getElementById('next'); num = 1; next.onclick = function(){ nextImg(); } function nextImg(){ if (num===4){ num = 1; } imgBox.src = `images/${num}.jpg`; num++; }s setInterval(function(){ nextImg(); }, 1000);
如下經常使用的幾種結點類型:javascript
元素類型 | 節點類型 |
---|---|
元素 | 1 |
屬性 | 2 |
文本 | 3 |
註釋 | 8 |
文檔 | 9 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>節點屬性</title> </head> <body> <div id="box">我是一個文本節點<!-- 我是註釋 --></div> <script type="text/javascript"> // 1.獲取元素節點 var divNode = document.getElementById('box'); console.log(divNode.nodeName + '|' + divNode.nodeValue + "/" + divNode.nodeType); // 2.獲取屬性節點 var attrNode = divNode.attributes[0]; console.log(attrNode.nodeName + '|' + attrNode.nodeValue + "/" + attrNode.nodeType); // 3.獲取文本節點 var textNode = divNode.childNodes[0]; console.log(textNode.nodeName + '|' + textNode.nodeValue + "/" + textNode.nodeType); // 4.獲取註釋節點 var commentNode = divNode.childNodes[1]; console.log(commentNode.nodeName + '|' + commentNode.nodeValue + "/" + commentNode.nodeType); // 5.文檔節點 console.log(document.nodeName + '|' + document.nodeValue + "/" + document.nodeType); </script> </body> </html>
// 非嚴格模式 function fn(){ // this是window console.log(this); } // 嚴格模式 function fn(){ 'use strict'; // this是undifinded console.log(this); }
console.dir($); // jquery包含大量方法的對象 console.log($('#box')); // jquery對象,僞數組 console.log($('#box')[0]); // jquery對象轉節點對像 var box = document.getElementById('box'); // js對象 $(box); // js轉jq對象
console.log($('.box>p')) // 子代選擇器,jquery對象 console.log($('.box>p')[1]) // 組合選擇器 $('box,active') // 交集選擇器 $('div.active') // js對象 console.log($('input[type=text]')); // 屬性選擇器
$('#box.active').click(function(){ // this指向當前js節點對象 console.log(this); // 樣式操做 this.style.... // js轉換爲jq,操做樣式,不會覆蓋 $(this).css('color', 'red'); $(this).css('font-size'(或使用駝峯), '20px'); // 或使用對象傳值,遍歷對象進行賦值 $(this).css({'color':'red', 'font-size':40}); console.log($(this).css('color')); });
// 單獨設置樣式。不一樣種類的樣式不會覆蓋 $(this).css('font-size', '40px'); $(this).css('color','lightblue'); // 共同設置樣式 $(this).css({ 'font-size':'40px', 'color':'red', }) // 獲取屬性值 console.log($(this).css('color'));\
// eq,gt,lt,odd,even,first,last console.log($('ul li')[1]; // js對象 console.log($('ul li:eq(1)')); // jq對象 console.log($('ul li:gt(1)')); // 。。。 console.log($('ul li:lt(1)')); // 。。。 console.log($('ul li:odd')); // 。。。 console.log($('ul li:even')); // 。。。 console.log($('ul li:first')); // 。。。 console.log($('ul li:last')); // 。。。
// 選中後代全部的span/a .find() console.log($('ul').find('span')); console.log($('ul').find('a')); // 選中子代中的元素 console.log($('ul').children()); // parent(), document-html-body-... console.log($('span').parent()); // console.log($('ul li').eq(1)); // siblings(),實現選項卡,排他性 console.log($('li').addClass('active').siblings('button').removeClass('active')); // 當前點擊元素索引 var index = $(this).index(); $('p').eq($(this).index()).addClass('active').siblings('p').removeClass('active')
console.log($('span').parent().parent().parent().parent().parent());
// 選項卡方法一 for (var i = 0; i < btns.length; i++){ btns[i].index = i; btns[i].onclick = function(){ for (var j = 0; j < btns.length; j++){ // console.log(this); btns[j].className = ''; p[j].className = ''; } this.className = 'active'; p[this.index].className = 'active'; } } // 選項卡方法二 for (let i = 0; i < btns.length; i++){ btns[i].onclick = function(){ for (var j = 0; j < btns.length; j++){ btns[j].className = ''; p[j].className = ''; } this.className = 'active'; p[i].className = 'active'; } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jq實現選項卡</title> <style type="text/css"> button.active{ color: red; } p{ display: none; } p.active{ display: block; } </style> </head> <body> <button class="active">熱門</button> <button>電腦影音</button> <button>電腦</button> <button>家電</button> <p class="active">熱門</p> <p>電腦影音</p> <p>電腦</p> <p>家電</p> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> console.log($('button')); $('button').click(function(){ // 處理點擊的選項卡 console.log($(this)); $(this).addClass('active').siblings('button').removeClass('active'); // 獲取當前對象的索引 console.log(($(this).index())); $('p').eq($(this).index()).addClass('active').siblings('p').removeClass('active'); }); </script> </body> </html>
hellocss
)$('#button').click(function(){ // $('#box').show(2000); if($(this).text() === '顯示'){ $('#box').show(2000 function(){ $('#button').text() === '隱藏'); }); })else{ $(this).text() === '顯示'); $('#box').hide(2000); }
// 在開啓定時器時,須要先中止以前的定時器 $('#box').stop().toggle(2000); $('#box').slideDown(2000); $('#box').slideUp(2000);
$('#box').fadeIn(2000); $('#box').fadeOut(2000); // 動畫不支持背景色,須要插件支持 $('#box').animater([params], speed, callback);
$('#box').toggle(2000, function(){});
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> div { position: absolute; left: 20px; top: 30px; width: 100px; height: 100px; background-color: green; } </style> <script src="js/jquery.js"></script> <script> jQuery(function () { $("button").click(function () { var json = {"width": 500, "height": 500, "left": 300, "top": 300, "border-radius": 100}; var json2 = { "width": 100, "height": 100, "left": 100, "top": 100, "border-radius": 100, "background-color": "red" }; //自定義動畫 $("div").animate(json, 1000, function () { $("div").animate(json2, 1000, function () { alert("動畫執行完畢!"); }); }); }) }) </script> </head> <body> <button>自定義動畫</button> <div></div> </body> </html>
// 文檔加載jq中 $(document).ready(function(){$('p')}); // 文檔加載完成後,調用回調函數,無覆蓋現象 jQuery(function(){}); $(function(){ $('p').attr('title', 'henry'); $('p').attr({'title':'henry', 'color':'red'}); // 得到屬性,須要一個屬性名 $('p').attr('title'); // 移除(一個或多個) $('p').removeAttr('title id a'); }); // js中使用,js中的事件有覆蓋現象 window.onload = function(){ console.log(222); }; window.onload = function(){ console.log(111); }
$(function(){ $('input[type=radio]').eq(0).prop('checked'); $('input[type=radio]').eq(0).prop('type'); // 只能操做標籤上的屬性 $('input[type=radio]').eq(0).attr('a', 1); // 能夠操做對象內部的屬性 $('input[type=radio]').eq(0).prop('type'); });
<h2>視頻</h2> <video width="" height="" controls="controls"> <source src="知乎.mp4" type="video/mp4"></source> </video> // controls表示播放按鈕 <h2>音頻</h2> <audio src="海賊王%20-%20ビンクスの酒(獨唱).mp3" controls="controls">音頻</audio>
$('#box').append('henry'); // 追加一個標籤 $('#box').append('<h2>echo</h2>'); $('#box').append(js對象); // 若是參數是jq對象至關於移動操做 $('#box').append(jq對象);
$('<a href="">百度一下 </a>').appendTo('#box'); // 鏈式編程思想,能夠直接修改樣式 $('<a href="">百度一下 </a>').appendTo('#box').css('yellow');
$('#box').prepend('<h2>echo</h2>');
$('<a href="">百度一下 </a>').prependTo('#box');
$('h2').before('henry');
$('<a href="">百度一下 </a>').insertBefore('h2');
$('#box ul').replaceWith('<a href="">百度一下</a>'); // .replaceAll()和.replaceWith()功能相似,可是目標和源相反。 $('<a href="">百度一下</a>').replaceAll('#box ul');
// 刪除 $('button').click(function(){ alert(111); $(this).css('color', 'red'); $('#box').append($(this).remove()); })
// 不刪除事件 $('button').click(function(){ alert(111); $(this).css('color', 'red'); $('#box').append($(this).detach()); })
$('#box').empty(); $('#box').html('');
$('#box').mouseover(function(){ console.log('進來了'); }) $('#box').mouseout(function(){ console.log('出去了'); })
// mouseover的傳播效應 $('#box').mouseover(function(){ console.log('進來了'); $('#child').stop().slideDown(1000); }) $('#box').mouseout(function(){ console.log('出去了'); $('#child').stop().slideUp(1000); })
// mouseenter $('#box').mouseenter(function(){ console.log('進來了'); $('#child').stop().slideDown(1000); }) $('#box').mouseleave(function(){ console.log('出去了'); $('#child').stop().slideUp(1000); })
$('#box').hover(function(){ },function(){})
// 默認加載頁面,聚焦 $('input[type=text]').focus(); // 聚焦事件 $('input[type=text]').focus(function(){ console.log('聚焦了'); }) // 失焦事件 $('input[type=text]').blur(function(){ console.log('失焦了'); })
$('input[type=text]').keydown(function(e){ console.log(e.keyCode); switch (e.keyCode){ case 8: $(this).val(''); break; default: break; } })
// 阻止默認事件方法1 <a href='javascript:void(0);'>; <a href='javascript:;'>; <form action='javascript:;'>; // 阻止默認事件方法2 <script type="text/javascript"> $('form').submit(function(e){ e.preventDefault(); console.log('11111'); }) </script>
// ajax,只針對與當前頁面的局部進行刷新 var name = $('input[type=text]').val(); var pwd = $('input[type=password]').val(); $.ajax({ url:'', method:'post'; data:{ a:name, b:pwd }, success:function(res){ // {data:200} if (res.data==200){ setTimeout(function(){ windown.open('網址', '_self') },3000) } } });
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div id="box"> </div> <script type="text/javascript"> $(function(){ $.ajax({ url:'https://api.apeland.cn/api/banner/', methods:'get', success:function(res){ console.log(res); // 根據響應中的data,判斷響應是否成功,以及就數據進行操做 if (res.code === 0 ){ var name = res.data[0].name; var cover = res.data[0].cover; $('#box').append(`<img src=${cover} alt=${name}>`); } }, // 出現錯誤時的操做 err:function(err){ console.log(err); }, }) }) </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ajax練習</title> <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div id="box"> <ul type='none'></ul> </div> <div id="content"> <ul></ul> </div1> <script type="text/javascript"> // 獲取導航頭 $.ajax({ url:'https://www.luffycity.com/api/v1/course_sub/category/list/', methods:'get', success:function(res){ console.log(res); $(`<li style='font-weight:bold')>所有<\/li>`).appendTo('#box ul').attr('id', 0); if (res.error_no===0){ res.data.forEach(function(item,index){ $(`<li type='none' style='font-weight:bold')>${item.name}<\/li>`).appendTo('#box ul').attr('id', item.id); }) } } }) // 獲取課程 var sub_category = 0; function get_course_list(sub_category){ $.ajax({ url:`https:\/\/www.luffycity.com/api/v1/courses/?sub_category=${sub_category}&ordering=`, method:'get', success:function(res){ $('#content ul').empty(); if (res.error_no===0){ res.data.forEach(function(item, index){ $(`<li>${item.name}<\/li>`).appendTo('#content ul').attr('id', item.id); }) } } }) } get_course_list(sub_category); // jq中的事件委託 $('#box ul').on('click', 'li', function(){ var sub_category = $(this).attr('id'); get_course_list(sub_category); }); </script> </body> </html>