Home >Web Front-end >JS Tutorial >JavaScript method to get the next node of dom_javascript skills

JavaScript method to get the next node of dom_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:37:011436browse

Use javascript to write a method to add up numbers by clicking the add and subtract buttons on the page.

The simple html is probably like this. Just understand and don’t worry about these details

<input type="button" value="+" onclick="jia(this)" />
<label class="num">0</label>
<input type="button" value="-" onclick="jian(this)" />

It looks like this

The javascript code is as follows

<script type="text/javascript">
function jia(a)
{
var nextnode = a.nextElementSibling;//获取下一个节点

alert(nextnode.innerHTML);
var a = parseInt(nextnode.innerHTML)
a += 1;
nextnode.innerHTML = a;
}
function jian(a) {
var previousnode = a.previousElementSibling;
var a = parseInt(previousnode.innerHTML)
a -= 1;
a = a > 0 &#63; a : 0;
previousnode.innerHTML = a;
}
</script>

Explain:

function jian(a) and

function jia(a) is the currently clicked object. Add this to the onclick event method;

- nextElementSibling gets the next node of the current node (gets the next sibling node)
- previousElementSibling gets the previous node of the current node

Note: IE will skip document nodes with spaces (such as newline characters) generated between nodes, but Mozilla will not do this - FF will read layout elements such as spaces and newlines as nodes, so , the next node element that can be read using nextSibling in IE needs to be written like this in FF: nextElementSibling.

The above explanation means using nextElementSibling and previousElementSibling to obtain the next sibling node and the previous sibling node. You can remove line breaks, spaces, etc., and directly find our label element. But the following two

nextSibling
previousSibling also refers to the next sibling node and the previous sibling node, but it is easy to use in IE
--------------------Explanation of keywords

parseInt conversion function.

a = a > 0 ? a : 0;----ternary expression.

Statement:
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