var morningAlarm = '6:30AM';
morningAlarm = "7:20AM";
if 条件
if () { } else { }
可以用switch代替if
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var moonPhase = 'full';
switch(moonPhase) {
case 'full':
console.log('Howwlll');
break;
case 'mostly full':
console.log('Arms and legs are getting hairier');
break;
case 'mostly new':
console.log('Back on two feet');
break;
default:
console.log('Invalid moon phase');
break;
}
var myPlaces = ['Place2','London','Berlin'];
var friendPlaces = ['Place1','Place2','Spot3'];
for (var i = 0; i<myPlaces.length; i++) {
console.log(myPlaces[i]);
for (var j =0; j<friendPlaces.length; j++) {
if (myPlaces[i] === friendPlaces[j]) {
console.log(myPlaces[i]);
}
}
}
变量操作
1
2
3
4
5
myPlaces.push("Beijing") // add to end
myPlaces.pop() // delete last
myPlaces.unshift("Frankfurt") // add to start
myPlaces.shift() // delete first
myPlaces.length // variable length
调用html元素
var example-class = document.getElementsByClassName('example-class-name');
var header = document.getElementsByTagName('header');
header.innerHTML = "<p> This is header </p>"; // change element content
jQuery简化
$('example-tag-name'); // tag name
$('.example-class-name'); // class name
$('#example-id-name'); // id name
$('tag-name.class-name'); // combination of tag and class name
Get element and change its attribute
var firstPlan = document.getElementById('plan1');
firstPlan.className = "delete"; // change class="" to "delete"
firstPlan.textContent = "Finished plan";
Siblings and parents
var firstPlan = document.getElementById('plan1');
var secondPlan = firstPlan.nextSibling; // next neighbour node
secondPlan.ClassName = "finish";
var parentPlan = firstPlan.parentNode; // upper level node
var childPlan1 = parentPlan.firstChild; // child node
jQuery 显示隐藏示例
1
2
3
4
5
6
7
8
9
10
function main() {
$('.projects').hide(); // $('.projects').fadeIn(400);
$('.projects-button').on('click', function() {
$(this).toggleClass('active'); // toggle on and off
$(this).text('Projects Viewed');
$(this).next().slideToggle(400); // next = following class
});
}
$(document).ready(main);
系统通知
alert("It's done")
confirm("You are going to close the window")
prompt("What's your name?")
创建object
1
2
3
4
5
var car = new Object();
car.color = "red";
car.changeColor = function(anothercolor) {
this.color = anothercolor;
}
OR to use literal notation
1
2
3
4
5
6
7
8
var car = {
color: "red", // separate attribut and valus with ':', and variables with ','
maker: "Ford",
changeColor: function(anothercolor) {
this.color = anothercolor;
document.write("The car is now" + this.color);
}
}