i am replacing the img src attribute using javascript
my code is
<div class="reader" id="reader1"></div>
<img src="images/img_001.jpg" alt="image" id="image1"/>
</div>
and javascript code
$("#image1").attr("src").replace("images/img_001.jpg", "images/img_002.jpg");
the src attribute is not replacing
您不需要调用replace()
,只需设置新的src即可:
$("#image1").attr("src", "images/img_002.jpg");
参见http://api.jquery.com/attr/#attr2 :
$("#image1").attr("src", "images/img_002.jpg");
You can change a value using
$('#image1').attr('src', 'images/img_002.jpg');
If you are using:
$('#image1').attr('src');
The function will return a string. String do NOT get passed by reference, but get copied instead. So modifying it doesn't actually change it.
You can directly set the value of src
with:
$("#image1").attr("src", "images/img_002.jpg");
Have a look at jQuery doc for attr()
.
The reason is because the replace
method actually returns the new string - not edits it in place.
You can achieve what you want like this:
$("#image1").attr("src", function(){
return $(this).attr('src').replace("images/img_001.jpg", "images/img_002.jpg");
});
This sets a new value to the src
attribute by calling the function (second parameter). This function actiually returns
the replaced value.
Live example (check the src with developer tools): http://jsfiddle.net/4K3Dy/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.