0

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?

1
  • Try to set the href of that link and you'll see why :-) Commented Jun 20, 2015 at 14:38

3 Answers 3

2

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" />
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.