js simple entry

A, JavaScript Introduction

JavaScript is the main language of the page to complete data validation. It runs on the client, you need to run the browser to parse execute javascript code.

js weak type, i.e. the type of variable. For example, for a variable that can be integer, or a string.

Features:

  1. Interactivity (it can do dynamic interactive information)
  2. Security (do not allow direct access to the local hard disk)
  3. Cross-platform (as long as it can be interpreted js browser can perform, and platform-independent)

Second, the basic knowledge (there may skip the basics of programming)

1), the output statement

There are three js output.

  1. alert (): a pop-up warning box, the text is output to the alert box
  2. document.write (): output text in the body
  3. console.log (): output text on the console. Press F12 to check the browser element, you can see the text on the console output.

2), js write position

1. js code may be written to the tag onclick attribute

<!--点击按钮会弹出弹窗-->
<button onclick="alert('标签onclick中的js代码')">点我</button>

2. js code written in hyperlink href attribute, click the hyperlink, js code execution

<a href="javascript:alert('超链接中的js代码');">点我</a>
<a href="javascript:;">点我</a>

3. Write the script tag, open the page on the implementation of

<script type="text/javascript">    
   alert("这是我的第一个js代码");
</script>

4. in an external file, and then introduced (recommended)

Note: Once a script tag to introduce external js file, you can not write internal js code inside, even if writing will be ignored. If necessary, write another script in.

<script type="text/javascript" src="js文件路径"></script>

3), the basic syntax

1. Single-line comments

//单行注释

2. Multi-line comments

/*
 *	这是多行注释
 */

3.js strictly case sensitive

4.js each statement ends with a semicolon

5.js ignores multiple spaces and line breaks

4), literals and variables

Literal: immutable values, for example: 12345. It can be used directly.

Variable: to save the literal value of the variable may be arbitrarily changed. Ease of use of the literal.

Declare variables: use the var keyword to declare a variable in js

5), an identifier

Js can be made in all our own name can be called identifiers.

Such as: variable names, function names, attribute names.

Naming rules:

  1. Identifiers may be characters, numbers, _, $ Composition
  2. Identifiers can not begin with a number
  3. JS identifier can not be a keyword or reserved words
  4. Generally use nomenclature hump
  5. js underlying save identifiers actually uses a unicode encoding (utf-8), so in theory, all of the content contained in utf-8 can be used as identifiers, including the Chinese, but not recommended.

Third, the data type

Data type is the type literal. js in a total of six data types. String, Number, Boolean, Null, Undefined, Object. The first five are the basic data types, object to reference data types.

1), String string

  • Quotes the literal amount
  • Double or single quotes. For single string or double quotes use of different quoted
var str = 'js:"hello"';
  • You can use the string \ as an escape character, represent some special symbols can be used \ to escape
var str = "js:\"hello\"";

2), Number value

  • All values ​​are in js Number type. Including integer and floating point (decimal)

  • You can use typeof to check the type of a variable.

  • It represents the maximum numerical Number.MAX_VALUE. When this value is exceeded, it becomes a positive infinity Infinity

  • NaN: not a number. This value is obtained when two strings arithmetic operations. In + is string concatenation string operations, instead of arithmetic addition.

  • String and Number types are added still do string concatenation

3), Boolean Boolean value

Only two values ​​true or false. Used for logical judgment.

4), Null null

The null value is used to represent a special null object

5), Undefined Undefined

All js variables when given the initial value, the default value is undefined

6), Object Object

Fourth, the operator

1), relational operators

Equal to: == relatively simple digital denomination

Full equal to: compare literals, there are more types of data in addition ===

2), a logic operation

And operations: &&

OR: ||

The negation operator:!

In js, all variables can be used as a boolean types. 0, null, undefined, empty string by default is false

V. Array

Array definition mode

var 数组名=[];//空数组
var 数组名=[true,1,"abc"];//定义并赋值

Js type of value in an array which may be different

Js in an array of languages, as long as we pass the array subscript assignment, the maximum value of the index, will be automatically assigned to the array

var arr=[]
arr[0]=1;
alert(arr.length); //1
arr[2]=3;
alert(arr.length); //3

Six function

1), the function is defined:

1. Use the function keyword to define a function

function 函数名(参数列表){
    函数体;
}

2. The second way is defined

var 函数名= function(参数列表){
    函数体;
}

Do not specify the type parameter. If the function has a return value, to return directly.

js function overloading is not allowed, a function of the overloaded function overrides.

2), arguments stealth function parameters (only function within function)

Need not be defined in function is the function, but it can be directly used to obtain all the parameters of the variable, called hidden parameters.

Java and variable length parameter (Object ... args) Like

function fun() {
    alert(arguments[0]);
    alert(arguments[1]);
    alert(arguments[2]);
}
fun(1, '2', true);

Seven custom object

1), Object in the form of custom objects

Definition of an object

var 对象名 = new Object(); //对象实例
对象名.属性名= 值;		//定义一个属性
对象名.函数名 = function(){}  //定义一个函数

Access to objects

对象名.属性名|函数名()

Example:

var obj = new Object();
obj.name = "张三";
obj.age = 20;
obj.fun = function() {
    alert("name=" + this.name + ",年龄=" + this.age);
}
obj.fun();

2), braces in the form of custom objects

Object Definition

var 对象名 = {};//空对象
var 对象名={
    属性名:值,//定义一个属性
    属性名:值,
    函数名:function(){}//定义一个函数
}

Object Access

var obj = {
    name: "张三",
    age: 18,
    fun: function() {
        alert("name=" + this.name + ",age=" + this.age);
    }
}
obj.fun();

Eight events

1), commonly used in the event description

Event : computer input device to interact with the page in response, we called an event. Such as: mouse click, mouse sliding keyboard input.

Common events :

  • onload: loaded event. After the page loads, js code commonly used in the page initialization.
  • onclick: Click event. Commonly used in the click of a button response operation.
  • onblur: lost focus event. Enter the number of boxes used to validate the input focus back to the content is legitimate.
  • onchange: content change event occurs. Commonly used in the drop-down list box, and an input operation contents changed.
  • onsubmit: form submission event. Used before the form is submitted, verify that all forms phase is legitimate.

2), the registration of two event

Registration of events (binding), in fact, is to tell the browser when the incident response which operations are to be executed, called event registration or event binding.

  1. Static Event Registration: direct response given to the code after the event by the event attribute of html tags, called static registration.

  2. Dynamic registration event: means prior dom object label by js code, then the object name of the event by dom = function () {} This form gives the event a response code, called dynamic registration.

Dynamic registration of the basic steps:

  1. Gets the label of an object
  2. Label the object. Event name = function () {}

3), onload event

onload event is an event after the completion of parsing the page will automatically trigger the browser.

Static registration onload event

<body onload="alert('静态注册onload事件')">

onload event dynamic registration, the wording is fixed

<script type="text/javascript">
window.onload = function() {
            alert("动态注册onload事件");
        }
</script>

4), onclick event

Click event

Static registration onclick event

<script type="text/javascript">
    function onclickFun() {
                alert("静态注册onclick事件");
    }
</script>
<button onclick="onclickFun()">按钮1</button>

Dynamic registration onclick event

<script type="text/javascript">
        function onclickFun() {
            alert("静态注册onclick事件");
        }
        window.onload = function() {
            //1.获取标签对象。document是js提供的获取整个文档的对象
            var btn = document.getElementById("btn2");
            //2.标签对象.事件名=function(){}
            btn.onclick = function() {
                alert("动态注册onclick事件");
            }
        }
</script>
<button id="btn2">按钮2</button>

5), onblur event

Event loses focus

Static registration onblur event

<script type="text/javascript">
        function onblurFun() {
            console.log("文本框失去焦点");
        }
</script>
用户名:<input type="text" onblur="onblurFun()" />

Dynamic registration onblur event

<script type="text/javascript">
    function onblurFun() {
    	console.log("文本框失去焦点");
	}
    window.onload = function() {
        var pd = document.getElementById("password");
        pd.onblur = function() {
            console.log("动态注册失去焦点事件");
        }
    }
</script>
密码: <input type="password" id="password" />

6), onchange event

Static registration onchange event

<script type="text/javascript">
        function onchangeFun() {
            alert("选项已经改变");
        }
</script>
<select onchange="onchangeFun()">
        <option>选项1</option>
        <option>选项2</option>
        <option>选项3</option>
        <option>选项4</option>
</select>

Dynamic registration onchange event

<script type="text/javascript">
    window.onload = function() {
        var se = document.getElementById("select");
        se.onchange = function() {
            alert("选项已经改变");
        }
	}
</script>
<select onchange="onchangeFun()" id="select">
        <option>选项1</option>
        <option>选项2</option>
        <option>选项3</option>
        <option>选项4</option>
</select>

7), onsubmit event

A form is submitted

Static registration onsubmit event

<script type="text/javascript">
        function onsubmitFun() {
            alert("静态注册表单提交事件");
        }
</script>
<form action="#" method="get" onsubmit="onsubmitFun()">
        <button type="submit">提交</button>
</form>

We know form submission event is often used to verify that the data is valid, then how to stop the illegal submit it?

We can understand onsubmit when the value is equal to "return false", the form will not submit

<form action="#" method="get" onsubmit="return false">
        <button type="submit">提交</button>
    </form>

So we can function returns false test data is not lawful, so that the form will not be submitted.

But take note, onsubmitFun replace knowledge false, return still retained.

<script type="text/javascript">
        function onsubmitFun() {
            alert("静态注册表单提交事件");
    		return false;
        }
</script>
<form action="#" method="get" onsubmit="return onsubmitFun()">
        <button type="submit">提交</button>
</form>

Dynamic registration onsubmit event

<script type="text/javascript">
        window.onload = function() {
            var fm = document.getElementById("form");
            fm.onsubmit = function() {
                alert("动态注册表单提交事件");
                return false;
            }
        }
</script>
<form action="#" id="form">
        <button type="submit">提交</button>
</form>

Return false function directly in the event can submit the form to stop

Nine, DOM model

DOM (Document Object Model): Document Object Model

Popular speaking, is to document tags, attributes, text, converted into object to manage

1), Document Object

Document document code stored in the form of a tree structure

Document object of understanding:

  1. Document management of all html document content.
  2. document is a document tree with the structure, have a hierarchy.
  3. It allows us to put all the labels are objectified.
  4. We have access to all the label objects through the document. When we registered the previous dynamic event on the use of this.

html tags analog objectification

The following code div analog objectification

<body>
    <div id="div1">
        hello
    </div>
</body>

result:

class Dom{
    private String id; //id属性。跟标签有的属性对应
    private String tagName; //标签名。即div
    private Dom parentNode; //父亲。即body
    private List<Dom>children; //孩子节点
    private String innerHTML; //起始标签到结束标签中间的内容。即hello
}

2) the method of inquiry document

  1. document.getElementById (): query by the value of the id attribute of the element
  2. document.getElementsByName (): to query the value of the name attribute of the element by
  3. document.getElementsByTagName (): used to query elements by tag name
  4. document.getElementsByClassName (): Returns the name of all the elements of the specified class collection of documents, as the NodeList object
  5. document.getElementsByTagNameNS (): Returns all elements with the specified name and namespace of the NodeList.

When using the query, if there is an id attribute precedence getElementById, no id, priority use getElementsByName, are not, then use the getElementsByTagName.

3) Create html tags and displayed

<script type="text/javascript">
        window.onload = function() {
            var obj = document.createElement("div"); //在内存中
            obj.innerHTML = "今天天气很不错";
            document.body.appendChild(obj);//为body添加子标签
        }
</script>

Guess you like

Origin www.cnblogs.com/ylcc-zyq/p/12546912.html