简体   繁体   中英

Javascript: Split and variable issues

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?

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');
    }

    //-----------------//

} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM