JavaScript is a programming language that adds interactivity to your website (for example: games, responses when buttons are pressed or data enter in forms, dynamic styling, animation).
JavaScript is incredibly versatile. You can start small, with carousels, image galleries, fluctuating layouts, and responses to button clicks.
With more experience you'll be able to create games, animated 2D and 3D graphics, comprehensive database-driven apps, and much more!
- First, go to your test site and create a new folder named 'scripts' (without the quotes). Then, within the new scripts folder you just created, create a new file called
main.js
. Save it in yourscripts
folder. - Next, in your
index.html
file enter the following element on a new line just before the closing</body>
tag:<script src="scripts/main.js"></script>
- This is basically doing the same job as the
<link>
element for CSS — it applies the JavaScript to the page, so it can have an effect on the HTML (along with the CSS, and anything else on the page). - Now add the following code to the
main.js
file:var myHeading = document.querySelector('h1'); myHeading.textContent = 'Hello world! haha';
- Finally, make sure the HTML and JavaScript files are saved, and load
index.html
in the browser. You should see something like the following:
When wanting to do something to an element, you first need to select it.
解释一些javascript的主要特性
Variables
Variables are containers that you can store values in.
var myVariable;
变量可以是String, Number, Boolean, Array, Object.
Comments 和C++是一样的。
操作符 +- */基本也和C++一样的。
条件操作符
if else 语句
函数
var myVariable = document.querySelector('h1');
alert("hello!');
These functions, document.querySelector and alert, are built into the browser for you to use whenever you desire.
定义自己的函数
function multiply(num1, num2) {
var result = num1 * num2;
return result;
}
运行自己定义的函数
multiply(4, 7);
Event事件
点击事件
click event, which is fired by the browser when you click on something with your mouse.
document.querySelector('html').onclick = function() {
alert("Ouch! Stop poking me!');
}
高级操作
更换照片。
var myImage = document.querySelector('img');
myImage.onclick = function() {
var mySrc = myImage.getAttribute('src');
if(mySrc === 'images/firefox-icon.png') {
myImage.setAttribute ('src','images/firefox.png');
} else {
myImage.setAttribute ('src','images/firefox-icon.png');
}
}
写成这样,点击照片的时候就会更换照片。
增加按钮加入欢迎页面
var myButton = document.querySelector('button');
var myHeading = document.querySelector('h1');
function setUserName() {
var myName = prompt('Please enter your name.');
localStorage.setItem('name', myName);
myHeading.textContent = 'Mozilla is cool, ' + myName;
}
if(!localStorage.getItem('name')) {
setUserName();
} else {
var storedName = localStorage.getItem('name');
myHeading.textContent = 'Mozilla is cool, ' + storedName;
}
myButton.onclick = function() {
setUserName();
}