Home > Web Front-end > JS Tutorial > Pure JavaScript implementation to obtain the values ​​of onclick, onchange and other events_javascript skills

Pure JavaScript implementation to obtain the values ​​of onclick, onchange and other events_javascript skills

WBOY
Release: 2016-05-16 16:23:26
Original
1399 people have browsed it

When Xiaocai dealt with the cascading problem of drop-down menus today, I wanted to get the content of an event in the HTML tag, that is, the value, for example, from .

Xiaocai wanted to use the information in the event to determine the next level menu, but this seemingly simple question made Xiaocai tangled up.

If you know a little bit about JQuery, you may try to get it like this:

Copy code The code is as follows:

$(document).ready(function(){
var onchangeValue = $("#city").attr("onchange");
alert(onchangeValue);
});

Under normal circumstances, this can indeed be obtained, because JQuery’s universal attr method can obtain any "attribute" in the tag. Even if it is an event, the content can be obtained directly. Here onchange is the event.

But in the actual development environment, Xiaocai cannot be obtained using this method, and all obtained are undefined.

When I was struggling, I found another way to obtain it using pure JavaScript.

The specific code is as follows:

Copy code The 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 mainly used here. It obtains the attribute node, ignoring the difference between attributes and events, similar to the processing of XML, and then uses nodeValue to obtain the node value of the attribute node.

If you use the getAttribute() method, since onchange is an event, what you get is a function object and cannot be treated as a string.

I hope this article can help children’s shoes in need. . . . .

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template