Okay, I've been trying to test something new, as a feature to implement into my site. I can't seem to find out what is wrong. I want a feature called by an onclick event, that on each click, will cycle through a list.
Here's the test code I've tried with.
Code:
<html>
<head>
<script type="text/javascript">
var a = 0;
function test() {
var p = document.getElementById("test");
var type = ["<a href='http://www.yahoo.com'>Link to Yahoo</a>","<a href='http://www.google.com'>Link to google</a>"];
p.innerHTML = type[a];
var b = a + 1;
var a = b;
}
</script>
</head>
<body>
<button onclick="test()">Click here</button>
<p id="test">Starting text</p>
</body>
</html>
Each individual event works properly, but the overall function doesn't. Once reaching the function test(), the variable "a" is no longer assigned, and it prints "undefined" in the paragraph tag, since type[], has a selector value that is null. It cannot be included in the function itself, because it would be reassigned to, say 0 in this case, at the start of the function, and would not perform as intended. What I'm looking for this to do, is to pretty much count by adding 1 at each button press, and proceed to show a piece of HTML printed from the array. I could simply use a "if p = test[1], elseif p = test[2]... but that is somewhat impractical, to implement several dozen if/else statements. The strangest thing is that even with setting a global variable, the function doesn't seem to pull it in.
I normally test by placing intermittent alert(-variable-); in the code, to interrupt the code momentarily and state what the variable is set to, to help find out what happens, and it seems that when the function starts, it forgets the variable of "a".
<html>
<head>
<script type="text/javascript">
var a = 0;
function test() {
var p = document.getElementById("test");
var type = ["<a href='http://www.yahoo.com'>Link to Yahoo</a>","<a href='http://www.google.com'>Link to google</a>"];
p.innerHTML = type[a%2];
a++;
}
</script>
</head>
<body>
<button onclick="test()">Click here</button>
<p id="test">Starting text</p>
</body>
</html>
Thank you for that. With both of your help I have figured out what the issue was, and how to solve it. Declan, I understand where you're heading, but I have positioned everything in the test page, for organization purposes. But thank you vwphillips for the code, and Declan for explaining what it was I was doing wrong, and why vwphillips' response worked differently than mine.
Bookmarks