This article mainly introduces the method of obtaining the next node of dom using javascript to achieve the accumulation of numbers by clicking the add and subtract button on the page. Friends who need it can refer to the following
Use javascript to write a method of adding and subtracting by clicking on the page. Buttons realize the accumulation of numbers.
Simple html is probably like this. Just understand and don’t care 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
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 ? a : 0; previousnode.innerHTML = a; } </script>
Explain:
function jian(a) and
function jia(a) is the currently clicked object. Add this to the method connected to the onclick event;
- 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 the space document nodes (such as line feed characters) generated between nodes, but Mozilla will not do this - FF will treat layout elements such as space breaks and line feeds as node reads, so in IE The next node element that can be read using nextSibling in FF needs to be written like this: 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 refer to the next sibling node and the previous sibling node, but they are easy to use in IE
------------ --------Keyword explanation
parseInt conversion function.
a = a > 0 ? a : 0;----ternary expression.
Related recommendations:
JavaScript to get HTTP information in the navigation bar example sharing
JavaScript to get cookies and delete cookies detailed explanation
The above is the detailed content of JavaScript method to get the next node of dom. For more information, please follow other related articles on the PHP Chinese website!