jQuery - 如何在点击的元素上替换img src?

时间:2012-08-23 11:15:42

标签: jquery replace

HTML:

<div id="panel">
     <a href="path_to_image1.jpg" rel="shadowbox[page]">
     <img src="scripts/timthumb.php?src=path_to_image1.jpg&w=200&h=20" alt="Image name1" /></a>
</div>

<div id="thumbs">
    <a href="path_to_image1.jpg" rel="shadowbox[page]"><img src="scripts/timthumb.php?src=path_to_image1.jpg&w=30&h=30" alt="Image name1" /></a>
    <a href="path_to_image2.jpg" rel="shadowbox[page]"><img src="scripts/timthumb.php?src=path_to_image2.jpg&w=30&h=30" alt="Image name2" /></a>
    <a href="path_to_image3.jpg" rel="shadowbox[page]"><img src="scripts/timthumb.php?src=path_to_image3.jpg&w=30&h=30" alt="Image name3" /></a>
</div>

JS:

$('#thumbs a').click(function(evt) {
    evt.preventDefault();
    var clickedElement = $(this).clone();
    $('#panel').empty().append(clickedElement);
});

所以这是有效的,我只想将点击锚点上的w = 30&amp; h = 30的图像src更改为w = 200&amp; h = 200,然后将其附加到#panel。

2 个答案:

答案 0 :(得分:1)

$('#thumbs a').click(function(evt) {
    evt.preventDefault();
    var clickedElement = $(this).clone();
    var img = clickedElement.find('img'),
        imgSrc = img.attr('src').replace(/w=30&h=30/, 'w=200&h=200');

    img.attr('src', imgSrc);
    $('#panel').empty().append(clickedElement);
});

答案 1 :(得分:0)

$('#thumbs a').click(function(evt) {
    var clickedElement = $(this).clone().find('img').attr('src', function(i, src){
        return src.replace('w=30&h=30', 'w=200&h=200')
    }).end()
    $('#panel').html(clickedElement);
});

FIDDLE