斌斌学院(js笔记)

在JavaScript中,一切都是对象。

element=document.querySelector(selectors)

使用深度优先遍历,element是一个DOM元素,selectors是一个字符串,包含一个或者多个CSS选择器。如果没有找到匹配元素,则返回null,如果找到国歌匹配元素,则返回找到的第一个匹配到的元素。传递给 querySelector的字符串参数必须符合CSS语法。

document.getElementById(id);
document.getElementsByTag(classname);

通过id获取元素和通过class获取元素

Object.style.property;
Object.className;
Object.disabled;

改变元素样式、获取元素classname和设置元素disabled属性

4.js代码错误一般包括两种,语法错误和逻辑错误。

5.你可以先初始化变量然后再声明一个变量,这样与先声明变量再初始化是一样的。这叫做变量提升(var hoisting)。

6.变量命名习惯

An aside on variable naming rules

You can call a variable pretty much anything you like, but there are limitations. Generally you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.

You shouldn't use other characters because they may cause errors or be hard to understand by an international audience.

Don't use underscores at the start of variable names — this is used in certain JavaScript constructs to mean specific things, so may get confusing.

Don't use numbers at the start of variables. This isn't allowed and will cause an error.

A safe convention to stick to is so-called "lower camel case", where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words. We've been using this for our variable names in the article so far.

Make variable names intuitive, so they describe the data they contain. Don't just use single letters/numbers, or big long phrases.

Variables are case sensitive — so myage is a different variable to myAge.

One last point — you also need to avoid using JavaScript reserved words as your variable names — by this, we mean the words that make up the actual syntax of JavaScript! So you can't use words like var, function, let, and for as variable names. Browsers will recognize them as different code items, and so you'll get errors.

7.Variable types

There are a few different types of data we can store in variables (data types). In this section we'll describe these in brief, then in future articles you'll learn about them in more detail.

So far we've looked at the first two, but there are others.

Numbers

You can store numbers in variables, be those whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). JavaScript doesn't have different data types for different number types, like some programming languages do. When you give a variable a number value, you don't include quotes:

var myAge = 22;

Strings

Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks, otherwise JavaScript will try to intepret it as another variable name.

var dophinGoodbye="so long and thanks for all the fish";

Booleans

Booleans are true/false values — they can have two values, true or false. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:

var iAmAlive= true;

Whereas in reality it would be used more like this:

var test= 6<3;

This is using the "less than" operator (<) to test whether 6 is less than 3. As you might expect, it will return false, because 6 is not less than 3! You will learn a lot more about such operators later on in the course.

Arrays

An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try entering the following lines into your console:

var myNameArray=['Chris','Bob','Jim];
var myNumberArray=[10,15,45];

Arrays

An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try entering the following lines into your console:

myNameArray[0];
myNumberArray[2];

The square brackets here contain an index value that specifies the position of the value you want returned. You might have noticed that computers count from 0, instead of 1 like us humans do.

You'll learn a lot more about arrays in a future article.

Objects

In programming, an object is a structure of code that models a real life object. You can have a simple object that represents a car park and contains information about its width and length, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.

Try entering the following line into you console:

var dog={name:'Spot',breed:'Dalmatian'};

To retrieve the information stored in the object, you can use the following syntax:

dog.name

We won't be looking at objects any more for now — you can learn more about those in a future module.

8.Loose typing

JavaScript is a "loosely typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (e.g. number? string?).

For example if you declare a variable and give it a value with quotes round it, the browser will know it is a string:

var myString='hello';

It will still be a string, even if it contains numbers, so be careful:

var myNumber='500';
typeof(myNumber);
myNumber=500;
typeof(myNumber);

Try entering the four lines above into your console one by one, and see what the results are (don't type in the comments). You'll notice that we are using a special function called typeof() — this returns the data type of the variable you pass to it. The first time it is called in the above sequence, it should return string, as at that point the myNumber variable contains a string, '500'. Have a look and see what it returns the second time you call it.

8.数字类型

整数: 就是整数,例如 10, 400, 或者 -5.
浮点数: (浮点) 有小数点或小数位,例如 12.5,和 56.7786543。
双精度: 双精度是一种特定类型的浮点数,它们具有比标准浮点数更高的精度(这意味着它们精确到更大的小数位数)。

9.Comparison operators

You may see some people using == and != in their code for equality and non-equality — these are valid operators in JavaScript, but they differ from ===/!== — the former test whether the values are the same, but the datatype can be different, whereas the latter strict versions test if the value and the dataype are the same. The strict versions tend to result in less errors going undetected, so we are recommending that you use those.

10.Escaping characters in a string

To fix our previous problem code line, we need to escape the problem quote mark. Escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character. Try this:

var bigMouth='I\'ve got no right to take my place...';
var myNum=Number(myString);
var string=myNum.toString();

利用以上方法来进行字符串和数字类型的转换

12.Useful string methods

//在浏览器开发者控制台输入以下内容
var browser='mozilla';
browser.length;
browser[0];
browser.indexOf('zilla');
browser.slice(0,3);
browser.slice(2);
//slice的第二个值是可选的,如果输入的值是负数,那么代表length+index。
var rad="I Love You";
rad.toUpperCase();
rad.toLowerCase();
browser.replace('moz','van');

13.Some useful array methods

var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';
var myArray = myData.split(',');
myArray;
var myNewString = myArray.join(',');
myNewString;
myArray.push('Cardiff');
myArray;
myArray.push('Bradford', 'Brighton');
myArray;
var newLength = myArray.push('Bristol');
//array.push()会产生一个返回值,返回数组的长度
myArray;
newLength;
myArray.pop();
var removedItem = myArray.pop();
//array.pop返回删除的值
myArray;
removedItem;
myArray.unshift('Edinburgh');//返回数组长度
myArray;
var removedItem = myArray.shift();//返回删除的值
myArray;
removedItem;

14.conditional statement

Any value that is not false, undefined, null, 0, NaN, or an empty string ('') actually returns true when tested as a conditional statement.

switch(expression){
    case choice1:
        run this code
        break;
    case choice2:
        run this code
        break;

//include as many cases as you like

    default:
        actually,just run this code

15.Loop statement

iteration

16.Function

Functions versus methods

One thing we need to clear up before we move on — technically speaking, built in browser functions are not functions — they are methods.

The distinction is that methods are functions defined inside objects. Built-in browser functions (methods) and variables (which are called properties) are stored inside structured objects, to make the code more efficient and easier to handle.

Anonymous function

You can also assign an anonymous function to be the value of a variable, for example:

var myGreeting = function() {
  alert('hello');
}

myGreeting();

Note: The same scoping rules do not apply to loop (e.g. for() { ... }) and conditional blocks (e.g. if() { ... }) — they look very similar, but they are not the same thing! Take care not to get these confused.

17.Return Value

利用isNaN()来测试是否是一个数字。

18.Introduction to Events

Note that event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking they work together. The listener listens out for the event happening, and the handler is the code that is run in response to it happening.

Note: It is important to note that web events are not part of the core JavaScript language — they are defined as part of the JavaScript APIs built into the browser.

onclick
onfocus
onblur
ondblcilck
onkeypress
onkeyup
onkeydown
onmouseover
onmouseout

window.onkeypress, window.onkeydown, window.onkeyup — The color will change when a key is pressed on the keyboard. keypress refers to a general press (button down and then up), while keydown and keyup refer to just the key down and key up parts of the keystroke, respectively. Note that it doesn't work if you try to register this event handler on the button itself — we've had to register it on the button itself — we've had to register it on the window object, which represents the entire browser window.


You'll find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are just doing something really quick, but they very quickly become unmanageable and inefficient.

The newest type of event mechanism is defined in the Document Object Model (DOM) Level 2 Events Specification, which provides browsers with a new function — addEventListener(). This functions in a similar way to the event handler properties, but the syntax is obviously different. We could rewrite our random color example to look like this:

var btn = document.querySelector('button');

function bgChange() {
  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
  document.body.style.backgroundColor = rndCol;
}   

btn.addEventListener('click', bgChange);

Note that it is perfectly appropriate to put all the code inside the addEventListener() function, in an anonymous function, like this:

btn.addEventListener('click', function() {
  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
  document.body.style.backgroundColor = rndCol;
});

This mechanism has some advantages over the older mechanisms discussed earlier. For a start, there is a counterpart function, removeEventListener()
, which removes a previously added listener. For example, this would remove the listener set in the first code block in this section:

btn.removeEventListener('click', bgChange);

Second, you can also register multiple handlers for the same listener. The following two handlers would not be applied:

myElement.onclick = functionA;
myElement.onclick = functionB;

As the second line would overwrite the first value of onclick set. This would work, however:

myElement.addEventListener('click', functionA);
myElement.addEventListener('click', functionB);

Both functions would now run when the element is clicked.

What mechanism should I use?

Of the three mechanisms, you definitely shouldn't use the HTML event handler attributes — these are outdated, and bad practice, as mentioned above.

The other two are relatively interchangeable, at least for simple uses:

Event handler properties have less power and options, but better cross browser compatibility (being supported as far back as Internet Explorer 8). You should probably start with these as you are learning.

DOM Level 2 Events (addEventListener(), etc.) are more powerful, but can also become more complex and are less well supported (supported as far back as Internet Explorer 9). You should also experiment with these, and aim to use them where possible.

The main advantages of the third mechanism are that you can remove event handler code if needed, using removeEventListener(), and you can add multiple listeners of the same type to elements if required.

Event objects

Sometimes inside an event handler function you might see a parameter specified with a name such as event, evt, or simply e. This is called the event object, and it is automatically passed to event handlers to provide extra features and information. For example, let's rewrite our random color example again slightly:

function bgChange(e) {
  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
  e.target.style.backgroundColor = rndCol;
  console.log(e);
}  

btn.addEventListener('click', bgChange);

Here you can see that we are including an event object, e, in the function, and in the function setting a background color style on e.target — which is the button itself. The target property of the event object is always a reference to the element that the event has just occurred upon. So in this example we are setting a random background color on the button, not the page.

Preventing default behaviour

The trouble comes when the user has not submitted the data correctly — as a developer, you'll want to stop the submission to the server and give them an error message telling them what's wrong and what needs to be done to put things right. Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those, and implement your own validation checks. Let's look at a simple example.

var form = document.querySelector('form'); var fname = document.getElementById('fname'); var lname = document.getElementById('lname'); var submit = document.getElementById('submit'); var para = document.querySelector('p'); form.onsubmit = function(e) { if (fname.value === '' || lname.value === '') { e.preventDefault(); para.textContent = 'You need to fill in both names!'; } }

Event bubbling and capture

The final subject to cover here is something that you'll not come across often, but it can be a real pain if you don't understand it. Event bubbling and capture are two mechanisms that describe what happens when two handlers of the same event type are activated on one element. Let's look at an example to make this easier — open up the show-video-box.html example in a new tab (and the source code in another tab.) It is also available live below:

This is a pretty simple example that shows and hides a

with a

你可能感兴趣的:(斌斌学院(js笔记))