Obtain the values of onclick, onchange, and other events using pure JavaScript. onclickonchange

Source: Internet
Author: User

Obtain the values of onclick, onchange, and other events using pure JavaScript. onclickonchange

When you are dealing with the cascading problem of the drop-down menu, you want to obtain the content of an event in the HTML Tag, that is, the value, for example, from <select id = "city" onchange = "javascript: test (); "> </select> to obtain javascript: test ();.

The dish wants to determine the next menu through the information in the event, but this seemingly simple problem makes the dish tangle.

If you have a little understanding of JQuery, you may try to get it like this:

Copy codeThe Code is as follows:
$ (Document). ready (function (){
Var onchangeValue = $ ("# city"). attr ("onchange ");
Alert (onchangeValue );
});

In general, this can be obtained, because JQuery's omnipotent attr method can be used to obtain any "attribute" in the tag. Even if it is an event, the content can be directly obtained, here onchange is an event.

However, in the actual development environment, this method cannot be obtained, and all the results are undefined.

During the tangle, we found another method to implement acquisition using pure JavaScript.

The Code is as follows:

Copy codeThe Code is as follows:
$ (Document). ready (function (){
Var onchangeValue = document. getElementById ("city"). getAttributeNode ("onchange"). nodeValue;
Alert (onchangeValue );
});

To put it simply, the getAttributeNode () method is used here. It obtains attribute nodes and ignores the differences between attributes and events, similar to XML processing, then, use nodeValue to obtain the node value of the attribute node.

If the getAttribute () method is used, because onchange is an event, a function object is obtained and cannot be processed as a string.

Hope this article can help the children's shoes in need .....

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.