Ok I have this so far and it works to an extent,
$('a').click(function(e)
{
e.preventDefault();
var preFix = $(this).attr("href");
$('img.swap').each(
function() { this.src = this.src.replace('.gif', (preFix)+'.gif');
});
});
This pulls through the 'HREF' link and adds it to the end of the image. The problem is when I click the first link it swaps the images just fine but the second time I click one of the 5 links the image breaks.
I'm guessing its because it is just adding the 2nd prefix at the end of t开发者_JAVA百科he first. I have tried a few things but it just ends up breakin the whole thing.
There are two things i need it to do:
1) When you click one link then another I want to to remove the old prefix and tthe new one.
2) If the same link is clicked twice I need it to firstly add the prefix then just remove the prefix.
Many Thanks
Try this: :-D
$('img.swap').each(function{
$(this).data('current_image', this.src);
//saves the default image in data
})
$('a').click(function(e){
e.preventDefault();
var preFix = $(this).attr("href");
$('img.swap').each(
function() {
if($(this).data('prefix') != prefix){
this.src = $(this).data('current_image').replace('.gif', (preFix)+'.gif');
$(this).data('prefix', prefix)
}
else {
this.src = $(this).data('current_image');
$(this).data('prefix', '')
}
});
});
$(this).data(..)
stores a variable in that specific DOM element, than after doing that you can do boolean operations to chack it against the value you have :-)
It is more explained here: jQuery.data()
UPDATE
and instead of using an a (anchor) tag use something else with a className like .changeIMG:
<span class='changeIMG' postfix='-bw'>Change to black and white</span>
and with css it can look like an anchor tag:
span.changeIMG {
cursor: pointer;
color: blue;
text-decoration: underline;
}
and then there is 2 changes in the code above:
$('a').click(function(e){
become $('span.changeIMG').click(function(e){
and var preFix = $(this).attr("href");
become var preFix = $(this).attr("postfix");
$("img.swap").each(function(){
var origSrc = $(this).attr("src");
//original src can now always be accessed
$(this).attr("origSrc",origSrc);
});
$("a").click(function(e){
e.preventDefault();
var prefix = $(this).attr("href");
$("img.swap").each(function(){
var origSrc = $(this).attr("origSrc");
var newSrc = origSrc.replace(".gif",prefix+".gif");
$(this).attr("src",newSrc);
});
});
精彩评论