How to add events and select elements in js

Source: Internet
Author: User

Adding events in javascript is bound to events like jquery. To obtain elements, we can use getElementById directly. Next, let's take a closer look at how to add events in js and how to select elements.

I learned a few simple little effects today, mainly learning about statements, random numbers, setting element styles, and mouse events. I will share with you today.

The first is the move-in and move-out event. The HTML and JS Code is as follows:

The Code is as follows: Copy code

<Div id = "main">
<Label id = "tishi"> <input type = "checkbox"/> Automatic Login within two weeks </label>
<P id = "xinxi"> do not use this function on a public computer or Internet cafe for your information security! </P>
</Div>

Window. onload = function (){
Var oLabel = document. getElementById ('tishi ');
Var oP = document. getElementById ('xinxi ');

OLabel. onmouseover = function (){
OP. style. display = 'block ';
};
OLabel. onmouseout = function (){
OP. style. display = "none ";
};
};

Starting from the code on the outermost layer, onload is used because the browser parses the code from top to bottom in a row, so when it parses the code to var oLabel = document. getElementById ('tishi'), because the code in the body below has not been parsed, an error cannot be found. When you put the code in onload, after the webpage is loaded, the code in onload is executed.

Get the element. Here, we use the id to select the element getElementById (). Of course, the similar element is getElementsByTagName (). This is to select a group of elements by Tag Name and return the node list, it is a pity that the method of selecting elements through class is not used.

After the element is selected, an event is added to the element. When the mouse moves in and a prompt box is displayed, the onmouseover event is used to move the mouse over the oLabel, let the following prompt box display, the same is true for the onmouseout event. As for the display hiding, the display value of the element is changed. The hidden value is none, and the display value is other than none.

The second is click to show or hide:

The Code is as follows: Copy code

<Input type = "button" id = "btn" value = "show/hide www. bKjia. c0m"/>
<Div id = "div1"> </div>

Window. onload = function (){
Var oBtn = document. getElementById ('btn ');
Var oDiv = document. getElementById ('div1 ');
OBtn. onclick = function (){
If (oDiv. style. display = "block "){
ODiv. style. display = 'none ';
} Else {
ODiv. style. display = 'block ';
}
};
};

To judge the statement, because the major is the Java language, most of these basic statements are the same, but the effect in the above JS is still a little problem, when the page is loaded, clicking the first element will not hide. Why? Because JS modifies inline styles and, of course, it depends on inline styles when determining. After the page is loaded, div does not have inline styles. Therefore, when it is clicked for the first time, the div display is determined to be an empty string, and the Boolean value is false. Then the else statement is executed, so the div is still in the display status, which is easy to solve, you only need to write the judgment conditions in turn. The Code is as follows:

The Code is as follows: Copy code
Window. onload = function (){
Var oBtn = document. getElementById ('btn ');
Var oDiv = document. getElementById ('div1 ');
OBtn. onclick = function (){
If (oDiv. style. display = "none "){
ODiv. style. display = 'block ';
} Else {
ODiv. style. display = 'none ';
}
};
};

Another exercise similar to this principle is the display and hiding of the playlist, where the DEMO is located.

The third is a comprehensive exercise involving random numbers and random colors.

The Code is as follows: Copy code

<Div id = "div">
<Input type = "button" id = "changeWidth" value = "Change width"/>
<Input type = "button" id = "changeHeight" value = "Change height"/>
<Input type = "button" id = "changeColor" value = "change color"/>
<Input type = "button" id = "hidden" value = "hide"/>
<Input type = "button" id = "show" value = "show"/>
<Div id = "box"> </div>
</Div>

Window. onload = function (){
Var oWidth = document. getElementById ('changewidth ');
Var oColor = document. getElementById ('changecolor ');
Var oHeight = document. getElementById ('changeheight ');
Var oShow = document. getElementById ('show ');
Var oHidden = document. getElementById ('den den ');
Var oBox = document. getElementById ('box ');
OWidth. onclick = function (){
Var w = parseInt (Math. random () * 801 );
OBox. style. width = w + 'px ';
};
OHeight. onclick = function (){
Var h = parseInt (Math. random () * 601 );
OBox. style. height = h + 'px ';
};
OColor. onclick = function (){
Var r = parseInt (Math. random () * 256 );
Var g = parseInt (Math. random () * 256 );
Var bl = parseInt (Math. random () * 256 );
OBox. style. background = 'rgb ('+ r +', '+ g +', '+ bl + ')';
};
OShow. onclick = function (){
OBox. style. display = 'block ';
};
OHidden. onclick = function (){
OBox. style. display = 'none ';
};
};

Random Number. the random () method in the Math object can generate a random number between 0 and 1. The packet does not contain 0. This problem varies with the meaning of the packet, but does not contain 1. Take an integer. parseInt () is used to convert other types into integers. Well, the package does not contain 0. If it is set to an integer, it will certainly show 0. The principle of changing the width is to generate a random number of up to 800, and the height is the maximum of 600, because the number produced by random () is less than 1, if multiplied by 800, the maximum value is 799. the number of xxx. The maximum value after an integer is 799. Therefore, we need to multiply the value by 801 so that we can get the value 800. The following height and color are the same. The random color is represented by RGB. Three numbers ranging from 0 to 25 5 are randomly generated and placed in rgb. In this way, the random color effect is achieved.


Attached instances


Adding events to elements is the simplest way to add Javascript events with the best backward compatibility. For example:

<Input type = "text" value = "Happy everyday! "Onclick =" alert (this. value) "/> when you click a text field, the value of this text field attribute value is displayed." Happy everyday! ".

Generally, event processing involves not only alert (this. value), but also many lines of code. Therefore, the code is usually written to the event processing function and called by the onclick attribute.


Example 1: www. bKjia. c0m

The Code is as follows: Copy code

<Input type = "text" value = "Happy everyday! "Onclick =" myFunc () "/>

<Script>
Function myFunc (){
Alert (this. value); // output undefined
// More of the script statements
}
</Script>

After clicking the mouse, the result is undefined. Let's take a look at the following example:

Example 2:

The Code is as follows: Copy code

<Input type = "text" value = "Happy everyday! "Onclick =" myFunc () "/>

<Script>
Var value = 'Happy New Year! ';
Function myFunc (){
Alert (this. value); // output "Happy New Year! "
// More of the script statements
}
</Script>

The output is "Happy New Year! ", Based on the above two instances, we can conclude that this points to the window object, or the function myFunc cannot find its calling object, so the output is the value of the value Attribute of the window object" Happy New Year! ". Why does this point to the window object? See the instance:

Example 3:

The Code is as follows: Copy code

<Input type = "text" value = "Happy everyday! "Onclick =" myFunc (this) "/>

<Script>
Var value = 'Happy New Year! ';
Function myFunc (obj ){
Alert (obj. value); // output "Happy everyday! "
// More of the script statements
}
</Script>

We finally got the expected result "Happy everyday! ", According to Example 2 and Example 3, I came to an unofficial conclusion:

An anonymous function is initialized outside each event processing function. Therefore, the function myFunc cannot find its calling object. According to the js scope mechanism, this can only point to the window object, the following is an example of an inappropriate conclusion:

Example 4:

The Code is as follows: Copy code

<Input type = "text" value = "Happy everyday! "/>

<Script type = "text/javascript">
Var value = 'Happy New Year! ';
Function myFunc (){
Alert (this. value); // output "Happy New Year! "
// More of the script statements
}
Document. getElementsByTagName ('input') [0]. onclick = function (){
Alert (this. value); // output "Happy everyday! "
MyFunc (); // output "Happy New Year! "
}
</Script>

Now, the event analysis has been added to the element. Please advise!

In today's domestic Internet environment, adding events to html elements is still very common, but most of them are used in complicated front-end interactions. The most typical is mailbox. In various js frameworks, select addEventListener | attachEvent in a clear color, which is also recommended by w3c and the front-end developers. However, in a small project without a framework, we can select an object to add events.

Each method of adding events has advantages and disadvantages. Select "OK" based on the actual situation. In addition to adding events to elements, there are also four common methods to add events:

Object addition event:

The Code is as follows: Copy code

<Input type = "text" value = "Happy everyday! "/>

<Script>
Document. getElementsByTagName ('input') [0]. onclick = function (){
Alert (this. value );
}
</Script> <script for> identifier addition event:

<Input type = "text" id = "input" value = "Happy everyday! "/>

<Script for = "input" event = "onclick"> // The value of the for attribute is the id of the corresponding element.
Alert (this. value );
</Script>

Note: This method was first proposed by Microsoft and has not been adopted by w3c organizations so far, so it is only applicable to IE browsers. If this method is used, it means that you must create a <script for> identifier for each element to add events.

Add events using the attachEvent method:

The Code is as follows: Copy code

<Input type = "text" value = "Happy everyday! "/>

<Script>
Function myFunc (){
Alert (this. value); // output undefined
// More of the script statements
}
Document. getElementsByTagName ('input') [0]. attachEvent ("onclick", myFunc );
</Script>

Note: this method is also exclusive to ie. other browsers use the addEventListener method. Because the native attachEvent fails to bind this to the call object, the output is undefined, both John Resig and Dean Edwards can solve this problem. You can search for it by yourself!

Add an event using the addEventListener method:

The Code is as follows: Copy code

<Input type = "text" value = "Happy everyday! "/>

<Script>
Function myFunc (){
Alert (this. value );
}
Document. getElementsByTagName ('input') [0]. addEventListener ("click", myFunc );
</Script>

Note: This method is defined by W3C DOM standards.


For more dynamic positive events, see the following example.

Javascript dynamically adds events to elements in two cases:

Events without parameters and events with parameters.

1. events without parameters:

Two Methods: directly add events to objects and add events to nodes
For example, to add an onclick event whose id is tab1

First case:

The Code is as follows: Copy code

Var t = document. getElementById ("NewTitle ");
T. onclick = function showmsg (){
Alert ('Hello! World ');
}

The second case is more dynamic and practical. You can also add multiple functions (the order of the added events is the execution order ).

The Code is as follows: Copy code

Var tb = document. getElementById ("NewTitle ");
If (window. addEventListener) {// Mozilla, Netscape, Firefox
Td_value.addEventListener ('click', alert ('cc'), false );
Td_value.addEventListener ('click', alert ('cc'), false );
} Else {// IE
Td_value.attachEvent ('onclick', function () {alert ('changchange ');});
Td_value.attachEvent ('onclick', function () {alert ('changchange ');});
}

2. events with Parameters

The functionName here is the event processing function. What should I do if it contains parameters,
Some people say this:

The Code is as follows: Copy code

Element. onclick = function (sb ){
Alert (sb );
}

Is it the method above? The answer is incorrect.
Solution: anonymous functions:

The Code is as follows: Copy code

Element. onclick = function (){
FunctionName (param );
};

In this way, it is achieved through the anonymous method!

Make the best effort and pursue the highest achievement.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.