开发者

Javascript: Split and variable issues

In this code execution here:

h开发者_JS百科ttp://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');
    }

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

} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜