开发者

Click on a thumbnail, an image in a div changes

开发者 https://www.devze.com 2023-03-06 07:19 出处:网络
I am trying to do the following: a row with a couple of thumbnails that, when clicked, change an image in a mai开发者_运维知识库n div

I am trying to do the following:

What would be the best way to do this?

I tried something like this:

<a href="#" id="changeImage" rel="1"><img class="thumb" src="image1_thumb.jpg" /></a>
<div id="imageBox">&nbsp;</div>

and the jquery script

<script type="text/javascript">
$(document).ready(function(){
    $('#changeImage').click(function(){
        var $rel = $(this).find('a').attr('rel');
        $("#imageBox").html("<img src='image" + $rel + ".jpg' />");
    })
})

</script>

but it's not working.

Thanks for the help!


Try:

$(document).ready(function(){
    $('#changeImage').click(function(){
        var rel = $(this).attr('rel');
        $("#imageBox").html("<img src='image" + rel + ".jpg' />");
    })
});
  • Your original code is targeting an attribute of an anchor inside the 'changeImage' anchor. You were going one level too deep.
  • I also removed an unnecessary usage of $ with 'rel' variable.
  • And lastly, added a semicolon at the very end.

Also, I'd suggest you have a placeholder image (inside 'imageBox') and just change its 'src' attribute (instead of manipulating the DOM so much for no reason). Something like this:

$("#imageBox img").attr('src', 'image' + rel + '.jpg');


I think what you want is:

<script type="text/javascript">
$(document).ready(function(){
    $('#changeImage').click(function(){
        var $rel = $(this).attr('rel');
        $("#imageBox").html("<img src='image" + $rel + ".jpg' />");
    })
})

</script>

Because you clicked on the <a>, $(this) is the element with the rel attribute... The .find('a') was searching for a child element within the link you clicked.

Your code would have worked with this html:

<a href="#" id="changeImage">
    <a href="#" rel="1"><img class="thumb" src="image1_thumb.jpg" /></a>
</a>
<div id="imageBox">&nbsp;</div>

Which is obviously redundant...

Hope that helps :)


#changeImage should be .changeImage

0

精彩评论

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