0

In this code execution here:

http://sandrayoon.com/UAI/www3/newpin.php

I wrote a JS function that grabs the image source of the clicked icon and extracts the needed word into the "nr" variable:

var root='img/pins/'; 
var q=0; 
var nr;
function swapImg(ima){ 
//---extract pin----//
if(q==0)
{
nr = ima.getAttribute('src').split('/');
nr = nr[nr.length-1].split('.')[0]; 
nr = nr.split('1')[0];
}
else if(q==1)
{
nr = ima.getAttribute('src').split('/');
nr = nr[nr.length-1].split('.')[0]; 
nr = nr.split('2')[0];
}
//-----------------//
if(q==0)
{
ima.setAttribute('src',root+nr+'2.png');
q=1;
//document.write (nr); 
} 
else if(q==1)
{
ima.setAttribute('src',root+nr+'1.png');
q=0;
}
}

In this way, every time the icon is clicked, it changes the img src from "extractedword"1.png to "extractedword"2.png, back and forth.

My problem lies when more than one icon is selected and then another icon is selected - it adds an extra "1" or "2" at end of the "extractedword", messing up the img src link.

I think it's caused by all the icons sharing the same global variable of "nr" as their extracted word, but when I make it a local var inside the function it still doesn't work.

How can I remedy this problem?

asked Jul 7, 2011 at 14:50
1
  • Please indent your code! Commented Jul 7, 2011 at 15:23

1 Answer 1

1

I think your problem may have more to do with q as a global.

var root='img/pins/'; 
function swapImg(ima){ 
 //---extract pin----//
 var nr = ima.getAttribute('src').split('/');
 nr = nr[nr.length-1].split('.')[0]; 
 var q = nr.substring(nr.length-1,nr.length); 
 if(q==1) {
 nr = nr.split('1')[0];
 ima.setAttribute('src',root+nr+'2.png');
 } else if(q==2) {
 nr = nr.split('2')[0];
 ima.setAttribute('src',root+nr+'1.png');
 }
 //-----------------//
} 
answered Jul 7, 2011 at 15:25
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.