开发者

How to rewrite inner img tags source with new image path using JQuery

开发者 https://www.devze.com 2023-04-04 01:00 出处:网络
How to rewrite image path of following img tag with new image path while click o开发者_JAVA技巧n span element

How to rewrite image path of following img tag with new image path while click o开发者_JAVA技巧n span element

<span id="cc-element-1">
    <img src="http://localhost/example/orig/abc.jpg"/>
</span>

Expected result as follows,

<span id="cc-element-1">
    <img src="http://localhost/example/cloned/abc.jpg"/>
</span>


$('#cc-element-1').click(function() {
    var $img = $(this).children('img');
    $img.attr('src', $img.attr('src').replace(/orig/, 'cloned'));
});


If doing a read-modify-write on an attribute you should use the callback function based version of .attr over the code given by @Sahil:

$('#cc-element-1').click(function() {
    var $img = $(this).children('img');
    $img.attr('src', function(index, val) {
        return val.replace(/orig/, 'cloned'));
    });
});

This avoids the need to call $img.attr(src) twice - once to read and once to write.

It's therefore more efficient, particularly so if the original selector is non-trivial.


$("#cc-element-1 > img").click(function() {$(this).attr('src', 'http://localhost/example/cloned/abc.jpg')})


try something like this:

var newSrc = 'http://localhost/example/cloned/abc.jpg';

$('span#cc-element-1').click(function(){
     $(this).children('img').attr('src', newSrc);   
});

See an example here:

http://jsfiddle.net/expertCode/FdgzJ/

0

精彩评论

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

关注公众号