通过jquery更改图像src

时间:2017-07-23 16:14:11

标签: javascript jquery

<div id = "current">
  <img src = "dog.jpg">
</div>

我尝试将狗改为dog-small.jpg

$("#left").click(function(){
    var $current = $("#current");
    $current.children('img').attr('src').replace('.','-small.');
    console.log($current.children('img').attr('src').replace('.','-small.'));
});

控制台打印:dog-small.jpg - &gt;正确 但是图像在页面上没有变化,当我检查元素时,它的src仍然是dog-small.jpg

2 个答案:

答案 0 :(得分:0)

在这里,您将使用示例解决方案https://jsfiddle.net/2xacp15m/1/

var updatedSRC = "small-dog.jpg";

$('button').click(function(){
	console.log("Old: " +  $('#current').find('img').attr('src'));
   $('#current').find('img').attr('src', updatedSRC);
   
   console.log("Updated: " +  $('#current').find('img').attr('src'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "current">
  <img src = "dog.jpg">
</div>

<button type="submit">
  Submit
</button>

答案 1 :(得分:0)

您需要将新的src作为第二个参数传递给.attr()

$("#left").click(function(){
    var $current = $("#current");
    var newSrc = $current.children('img').attr('src').replace('.','-small.');
    $current.children('img').attr('src', newSrc);
    console.log($current.children('img').attr('src'));
});