2010-11-05 125 views
0

我正在努力与一个简单的切换。那么,它应该很简单。我正在访问论坛和主题,无法完成它的工作。jQuery在标签图像之间切换

我有三个选项卡的图像(不属于任何包的一部分),我只是想点击的图像切换到“开”和别人开关置于“OFF”

<img class="mastheadTab" id="products" src="#application.viewImageDIR#/tab_products_on.gif" width="119" height="31" hspace="4"> 

<img class="mastheadTab" id="suppliers" src="#application.viewImageDIR#/tab_suppliers_off.gif" width="117" height="31" hspace="4"> 

<img class="mastheadTab" id="buyers" src="#application.viewImageDIR#/tab_buyers_off.gif" width="117" height="31" hspace="4"> 

这里是我懈怠了jQuery,这是需要修复的。 不知何故,我需要重新初始化标签,因为点击互相交叉,在错误的位置显示错误的图像,直到第二次或第三次点击后才切换状态。

$(".mastheadTab").live("click", function(e) { 
var tab = $(this).attr("id") 

$('.mastheadTab').toggle(
    function(){$(this).attr("src", "/chinabuy-new/images/website/tab_" + tab + "_on.gif"); }, 
    function(){$(this).attr("src", "/chinabuy-new/images/website/tab_" + tab + "_off.gif"); } 
); 
e.preventDefault(); 
}); 

回答

0

您可以在点击时获得id,就像这样:

$(".mastheadTab").click(function(){ 
    //turn the others off 
    $(".mastheadTab").not(this).attr("src", function(i, src) { 
    return src.replace("_on", "_off"); 
    }); 
    //toggle this image's source 
    this.src = this.src.replace(/(_off|_on)/, function(i, m) { 
    return m == "_off" ? "_on" : "_off"; 
    }); 
}); 

目前你得到id的点击图像并附加切换设置的click每次处理程序。相反,只需使用上面的代码即可获得点击图像的id

+0

感谢尼克,这停止了交叉。还有两个问题: 1)需要两次点击才能在第一次加载时更改标签 2)我需要关闭 – Paul 2010-11-05 21:54:58

+0

@Paul上的其他标签 - 尝试更新后的答案,它应该解决这两个问题。 – 2010-11-05 22:01:21

+0

尼克,谢谢,但它仍然在做奇怪的事情。这里是一个链接,所以你可以看到发生了什么: http://www.china-buy.com/chinabuy-new/index.cfm – Paul 2010-11-05 22:14:02