Reputation: 103
I'm just learning Javascript after starting out in PHP.
I'm trying some basic stuff, but for some reason the below code doesn't act as I expect. I have researched it, and from what I can tell it should work.
<script type="text/javascript">
showIndex=4;
function test(){
showIndex++;
alert(showIndex);
}
</script>
I am calling the script with an image:
<div style="display:inline-block;margin-left:25px;">';
<a href="" onclick="test()" ><img src="_images/next.png" width="100" /> </a>
</div>
It runs fine the first time, but when I hit the button again, it still has the initial variable plus one. (which makes me think it's acting as a local variable...) It seem so straight forward... what am I doing wrong?
Upvotes: 0
Views: 46
Reputation: 3815
The empty href attribute on the <a>
tag is messing you up. Either remove the href attribute, or change it to #
or javascript:void(0)
Alternatively, you can call your method from the href attribute like this
<div style="display:inline-block;margin-left:25px;">';
<a href="javascript:test()" ><img src="_images/next.png" width="100" /> </a>
</div>
Upvotes: 0
Reputation: 19024
The empty link just reloads the page. You can insert #
in it:
<div style="display:inline-block;margin-left:25px;">
<a href="#" onclick="test()" >www </a>
</div>
Then everything works as intended.
Upvotes: 0
Reputation: 21575
Remove the <a>
and have the event on the image, it's refreshing the page. You don't need to have it wrapped in an <a>
tag for a onclick
event:
<img src="_images/next.png" onclick="test()" width="100" />
Upvotes: 2