I'm using jquery to pop up an AddThis share box when I click on a link that surrounds an image. It works great. The jquery code I'm using is here:
//added to show/hide add-this
$('a#slick-toggle').click(function() {
$('#atBox').toggle(100);
return false;
});
And this is my relevant html:
<a id="slick-toggle" href="#" title="Share">
<img src="images/navicon/navicon4_off.gif" alt="share" id="share" class="img-swap">
</a>
This makes a little div box appear that has some sharing icons. It's working as intended.
What I wanted to do was also make the image that is inside the anchor tags "switch" when the anchor tag was clicked on. Unfortunately the regular jquery image "onclick" scripts I found for doing that don't seem to work, presumably because the "link" is being clicked, not the image? Anyway, I tried "merging" the initial script with an image swapping script by doing the following, but no luck:
$('a#slick-toggle').click(function() {
if ($('#share').attr("class") == "img-swap") {
开发者_开发知识库 this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$('.img-swap').toggleClass("on");
$('#atBox').toggle(100);
return false;
});
It doesn't seem to matter what I put in that third line, I can't ever get the jquery to recognize that I'm referring to the image. I keep getting a "Cannot call method 'replace' of undefined" message. I've tried this, $('#share') and ('#share'), and they all give me the same message. I'm not too familiar with jquery but am I doing something obviously wrong in my script to refer to the image tag when the function is being called on the anchor onclick event?
Thanks!
You need to find the image inside since your click
handler is on the <a>
that wraps it, like this:
$('a#slick-toggle').click(function() {
var img = $(this).find("img")[0];
if ($('#share').attr("class") == "img-swap") {
img.src = img.src.replace("_off","_on");
} else {
img.src = img.src.replace("_on","_off");
}
$('.img-swap').toggleClass("on");
$('#atBox').toggle(100);
return false;
});
Or, switch things up a bit like this:
$('a#slick-toggle').click(function() {
var img = $('#share')[0], isSwap = img.className == "img-swap";
img.src = isSwap ? img.src.replace("_off","_on") : img.src.replace("_on","_off");
$('.img-swap').toggleClass("on");
$('#atBox').toggle(100);
return false;
});
Another alternative: try using .children() to select a child element of the current one you've clicked
$(this).children('> img')
In that case, the image that is a direct descendant of where the click function is called.
http://api.jquery.com/children/
精彩评论