【问题标题】:Javascript: Split and variable issuesJavascript:拆分和变量问题
【发布时间】:2011-07-07 14:50:35
【问题描述】:

在此代码执行中:

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

我写了一个 JS 函数,它抓取点击图标的图像源并将需要的单词提取到“nr”变量中:

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


}

这样,每次点击图标,都会将img src从“extractedword”1.png变为“extractedword”2.png,来回切换。

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.

我认为这是由于所有图标共享相同的全局变量“nr”作为它们提取的单词,但是当我将它设置为函数内的局部变量时,它仍然不起作用。

我该如何解决这个问题?

【问题讨论】:

  • 请缩进你的代码!

标签: javascript variables split


【解决方案1】:

我认为您的问题可能更多地与 q 作为全局有关。

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

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

} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多