Javascript:拆分和可变问题 [英] Javascript: Split and variable issues

查看:30
本文介绍了Javascript:拆分和可变问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码执行中:

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

我写了一个JS函数,抓取被点击图标的图片来源并将需要的词提取到nr"变量中:

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


}

这样,每次点击图标,都会将img src从"extractedword"1.png更改为"extractedword"2.png,来回切换.

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.

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"全局变量造成的,但是当我在函数内部将其设置为局部变量时,它仍然不起作用.

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?

推荐答案

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

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

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

} 

这篇关于Javascript:拆分和可变问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆