<script language="javascript" type="text/javascript">
var value1=0;
var total_no_div;
var previous;
function doSwap(val) {
divs=document.getElementById(form).getElementsByTagName(val);
document.write(divs);
}
</script>
</head>
<body onload="doSwap(0)">
<form>
<input type="button" id="button" value="previous" name="previous" onClick="doSwap(this.value);">
<input type="button" id="button" value="next" name="next" onClick="doSwap(this.value);">
<!--******************************************************************************-->
<div id="div1">
</div>
<div id="div2">
</div>
<div id="div3">
</div>
<div id="div4">
</div>
here i want to assign a total no div to a 开发者_StackOverflow社区variable,and set it to previous and next button for navigation.
Remember that the getElementsByTagName will return elements regardless of heiracy in the DOM tree relative to the form node, instead you should evaluate the childnodes of the form element to see which are divs.
For example:
var nodes = document.getElementById("form").childNodes;
var cnt = 0;
for (var i = 0, l = nodes.length; i < l; i++) {
if (nodes[i].tagName == "DIV") cnt++;
}
I think it is simpler to work with the div elements directly, instead of using the number of elements and then using a dynamically created id to access the div-element. Thus, I would try to do it as follows:
<html>
<head><title>Test</title></head>
<body>
..
<script language="javascript" type="text/javascript">
<!--
var current;
window.onload = function() {
current = findNext(document.getElementById('form_name').firstChild);
if(current) {
current.style.background = 'green';
}
};
function findNext(begin) {
var current = begin.nextSibling;
while(current && (current.nodeType!=1 || current.tagName!='DIV')) {
current = current.nextSibling;
}
return current;
}
function findPrev(begin) {
var current = begin.previousSibling;
while(current && (current.nodeType!=1 || current.tagName!='DIV')) {
current = current.previousSibling;
}
return current;
}
function setNext() {
if(current) {
var tmp = findNext(current);
if(tmp) {
current.style.background = '';
tmp.style.background = 'green';
current = tmp;
}
}
}
function setPrev() {
if(current) {
var tmp = findPrev(current);
if(tmp) {
current.style.background = '';
tmp.style.background = 'green';
current = tmp;
}
}
}
//-->
</script>
<form id="form_name">
...
<div> .. </div>
<div> .. </div>
<div> .. </div>
<div> .. </div>
...
<input type="button" onclick="setPrev()" value="Previous"/>
<input type="button" onclick="setNext()" value="Next"/>
...
</form>
..
</body>
</html>
精彩评论