开发者

Getting an attribute value from a parent function in jquery

开发者 https://www.devze.com 2023-03-27 06:30 出处:网络
I\'m new to jquery, so please forgive, well... everything! I have a \'header bar\' made up of about 10 small thumbnail-style images. I would like to be able to click on these images which would then

I'm new to jquery, so please forgive, well... everything!

I have a 'header bar' made up of about 10 small thumbnail-style images. I would like to be able to click on these images which would then change a larger side-bar image to show a larger version.

Which, with some fiddling about, I seemed to manage by using the following code for the images:

<img src="header_images\small1.jpg" alt="alttext"  class="hdrimage" id="1" data-bigimage="big1.jpg" />
<img src="header_images\thumb2.jpg" alt="alttext"  class="hdrimage" id="2" data-bigimage="bigger2.jpg" />

etc...

I then added some jquery code at the bottom of the page:

$(".hdrimage").bind('click', function() {
  $("#swappyimage").attr("src", "header_images/"+$(this).attr("data-bigimage"));     
})

I'm not sure if that was the best way to do it, but it seems to work fine.

I then thought it would be nice to fade-out the old image and fade-in the new one, so added a .fadeOut("slow"); to the click event, but on testing it doesn't wait until the fade is complete before it swaps the image. Thanks to Google, I discovered I need to use a callback f开发者_JS百科unction on the .fadeOut to achieve this, so I tried something like:

$(".hdrimage").bind('click', function() {
    $("#swappyimage").fadeOut('slow', function() {
      $("#swappyimage").attr("src", "header_images/"+$(this).attr("data-bigimage"));
    })
})

But this no longer works. I'm fairly sure it's because the $(this) is now referring to #swappyimage rather than the .hdrimage that was clicked. I can't figure-out how to reference the attribute I need from the thumbnail (.hdrimage) that is clicked to trigger the whole thing, so would appreciate some help.

I hope I explained that well enough!


Simply define a variable prior to the fadeOut call:

$(".hdrimage").bind('click', function() {
    var newSrc = "header_images/"+$(this).attr("data-bigimage");
    $("#swappyimage").fadeOut('slow', function() {
      $("#swappyimage").attr("src", newSrc);
    })
})

Also, I'm assuming you just left this part out, but you never fade the image back in.


You can use http://api.jquery.com/event.target/ and pass the event object through the functions to where you need it.

$(".hdrimage").bind('click', function(clickEvent) {
    $("#swappyimage").fadeOut('slow', function() {
      $("#swappyimage").attr("src", "header_images/"+$(clickEvent.target).attr("data-bigimage"));
    })
})


Just save your context,

$(".hdrimage").bind('click', function() {
   var self = this;
   $("#swappyimage").fadeOut('slow', function() {
     $("#swappyimage").attr("src", "header_images/"+$(self).attr("data-bigimage"));
   })
})
0

精彩评论

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