Dynamically add events (sorting) in JS)

Source: Internet
Author: User

Adding events dynamically in JS involves browser compatibility issues. Based on my practical experience and some information collected from the Internet, I hope it will be useful.
 
Method 1: setattribute
VaR OBJ = Document. getelementbyid ("OBJ ");
OBJ. setattribute ("onclick", "javascript: Alert ('test ');");
Setattribute is used to specify the onclick attribute. However, setting style, onclick, and onmouseover attributes with setattribute does not work in IE. However, some attributes are acceptable. The following is an example of passing the test:
If you know the name of a control such as the select control, but this control does not set the ID attribute, in this case, the test in IE finds that attributes and events cannot be dynamically added to the control only through the control name, because W3C allows duplicate name attributes.
Function Test (){
// Obtain all the controls whose tagnames are select using tags. A select set is returned.
VaR OBJ = Document. getelementbytagname ("select ");
// Obtain the number of select sets through obj. length, and match names one by one
For (VAR I = 0; I <obj. length; I ++ ){
// Find the select control whose name is part
If (OBJ [I]. Name = 'part '){
OBJ [I]. setattribute ("ID", "myid"); // set the ID to myid for the select control whose name is part.
OBJ [I]. setattribute ("onchange", myfunc); // you can call the myfunc function to set an onchange event for the control.
}
}
}
 
Function myfunc (){
Alert ("Test OK !");
}

Method 2: Use attachevent and addeventlistener
IE supports attachevent
OBJ. attachevent ("onclick", foo );
Function Foo ()
{
Alert ("test ");
}
Can also be written together
OBJ. attachevent ("onclick", function () {alert ("test ");});
Other browsers support addeventlistener
OBJ. addeventlistener ("click", Foo, false );
Function Foo ()
{
Alert ("test ");
}
Can also be written together
OBJ. addeventlistener ("click", function () {alert ("test") ;}, false );
Note that attachevent events include on, such as onclick, while addeventlistener does not include on, such as click.
By the way, the third parameter of addeventlistener (although rarely used) usecapture-if it is true, usecapture indicates that you want to start the capture. After capturing is started, all events of the specified type are assigned to the registered eventlistener before they are assigned to any eventtargets under the tree. The events that are going to bubbling through the tree will not trigger the specified eventlistener captured.
Comprehensive Application
VaR OBJ = Document. getelementbyid ("OBJ ");
If (window. addeventlistener ){
// Event code of other browsers: Mozilla, Netscape, and Firefox
// The Order of the added events is the execution order.
OBJ. addeventlistener ('click', alert ('test1'), false );
OBJ. addeventlistener ('click', alert ('test2'), false );
} Else {
// Ie Event code
OBJ. attachevent ('onclick', function () {alert ('test3 ');});
OBJ. attachevent ('onclick', function () {alert ('test4 ');});
}

Method 3: event = Function
Example: obj. onclick = Foo;
This is supported in multiple browsers. This is an old specification (method 2 belongs to the dom2 Specification). However, due to its ease of use, there are many applications.
 
Reprinted: getelementsbyname and getelementbyid
Address: http://www.jsxzinfo.com/blog/post/getElementByID.html
In the past, document. getelementbyid was often used to obtain the ID tag attribute in HTML. Yesterday, document. getelementbyname (note that there is no S) was used to retrieve the name tag attribute. the browser reports an error. After checking the information, we found that this function was not available. It should be getelementsbyname. And document. the difference between getelementbyid is that the former returns a set of names and IDs, because W3C allows duplicate names, that is, the same name can be used for HTML tags, the latter returns the first element of the ID. Therefore, document. getelementsbyname is usually used by document. getelementsbyname ("***") [0], [1], and so on. The results of methods such as document. getelementsbytagname and document. formname. elements are also set.
<Input type = checkbox value = 2> 2
<Input type = checkbox value = 1> 1
<Script language = "JavaScript">
VaR arr = Document. getelementsbytagname ("input"); // get all input, and the returned result is an array.
Alert (ARR [0]. Value); // obtain the value of the first input.
</SCRIPT>
 
Here is another example:
A table contains 7 or 8 tr values. I need to dynamically display 4 or 5 tr values = none/block. But I don't want to define an ID for each TR, So I thought of a common name for the four or five Tr and then returned an Array Using getelementsbyname, in this way, it is convenient to operate every TR in a loop, but later I found that IE does not support it.
If it is only an hide/show operation, you can set an independent stylesheet and set the object with the same classname to display: none. Then, you can change the show/hide status of the objects belonging to the classname by changing the disabled property of the stylesheet.
<HTML>
<Head>
<Title> test </title>
</Head>
<Body>
<Style id = "ABC-style">
. ABC {display: None}
</Style>
<H1 class = 'abc'> test <SCRIPT>
Function toggle (){
VaR style = Document. getelementbyid ('abc-style ');
Style. Disabled =! Style. Disabled;
}
</SCRIPT>
<P onclick = "toggle ()"> click me </P>
</Body>
</Html>
Extended thinking:

For example, if you want to get the TR of "ABC" for all the class attributes, you can use this:
Code:
Alltr = Document. Evaluate ("// tr [@ class = 'abc']", document, null, xpathresult. unordered_node_snapshot_type, null );
For (VAR I = 0; I <alltr. snapshotlength; I ++ ){
Tr = alltr. snapshotitem (I );
// Do something with TR
}

This article Reprinted from the network base camp: http://www.xrss.cn/Dev/Other/2007122118298.Html

 

======

 

The simplest is:
<Input type = "button" onclick = "alert (this. Value)" value = "I Am a button"/>
Dynamically add an onclick event:
<Input type = "button" value = "I Am a button" id = "bu">
<SCRIPT type = "text/JavaScript">
VaR bobj = Document. getelementbyid ("bu ");
Bobj. onclick = objclick;
Function objclick () {alert (this. Value )};
</SCRIPT>
If the anonymous function () {} is used, it is shown below:
<Input type = "button" value = "I Am a button" id = "bu">
<SCRIPT type = "text/JavaScript">
VaR bobj = Document. getelementbyid ("bu ");
Bobj. onclick = function () {alert (this. Value )};
</SCRIPT>
The above methods have the same principle. They all define the values of The onclick attribute. It is worth noting that if multiple definitions of obj. onclick, for example, obj. onclick = Method1; obj. onclick = method2; obj. onclick = method3, only the last defined obj. onclick = method3 takes effect. The previous two definitions overwrite the last one.
Let's look at attachevent in IE:
<Input type = "button" value = "I am Bin Laden" id = "bu">
<SCRIPT type = "text/JavaScript">
VaR bobj = Document. getelementbyid ("bu ");
Bobj. attachevent ("onclick", Method1 );
Bobj. attachevent ("onclick", method2 );
Bobj. attachevent ("onclick", method3 );
Function Method1 () {alert ("First Alert ")}
Function method2 () {alert ("second alert ")}
Function method3 () {alert ("third Alert ")}
</SCRIPT>
The execution sequence is method3> method2> Method1, Which is advanced and later, similar to the variables in the stack. Note that the first parameter in attachevent starts with "on", which can be "onclick/onmouseover/onfocus", etc.
It is said that (unconfirmed) it is best to use detachevent to release memory after using attachevent in IE
Let's take a look at addeventlistener in Firefox:
<Input type = "button" value = "I'm Bush" id = "bu">
<SCRIPT type = "text/JavaScript">
VaR bobj = Document. getelementbyid ("bu ");
Bobj. addeventlistener ("click", Method1, false );
Bobj. addeventlistener ("click", method2, false );
Bobj. addeventlistener ("click", method3, false );
Function Method1 () {alert ("First Alert ")}
Function method2 () {alert ("second alert ")}
Function method3 () {alert ("third Alert ")}
</SCRIPT>
We can see that the execution order in FF is Method1> method2> method3, which is just opposite to IE, first-in-first-out. Note that addeventlistener has three parameters. The first parameter is the name of an event without "on", such as click/Mouseover/focus.
This article from: the foot home (www.jb51.net) detailed source reference: http://www.jb51.net/article/11008.htm

 

 

 

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.