开发者

jQuery Toggle between tab images

I'm struggling with a simple toggle. Well, it should be simple. I'm visiting forums and threads and can't quite get it to work.

I have three tab images (not part of any package) and I simply want the clicked image to switch to "on" and others to switch to "off"

<img class="mastheadTab" id="products" src="#application.viewImageDIR#/tab_products_on.gif" width="119开发者_如何学Python" 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">

Here is my slack Jquery, which is in need of fixing. Somehow, I need to reinitialise the tabs, because the clicks are crossing over each other and displaying the wrong image in the wrong position and not switching states till after the second or third click.

$(".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();
});


You can get the id at the time of the click, like this:

$(".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";
  });
});

Currently you're getting the id for the clicked image and attaching a new toggle set of click handlers each time. Instead just use the code above to get th id for the image you clicked on.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜