[英]not replacing the img src attribute using jquery
i am replacing the img src attribute using javascript 我正在使用javascript替换img src属性
my code is 我的代码是
<div class="reader" id="reader1"></div>
<img src="images/img_001.jpg" alt="image" id="image1"/>
</div>
and javascript code 和javascript代码
$("#image1").attr("src").replace("images/img_001.jpg", "images/img_002.jpg");
the src attribute is not replacing src属性未替换
您不需要调用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: 您可以使用以下命令直接设置
src
的值:
$("#image1").attr("src", "images/img_002.jpg");
http://jsfiddle.net/VFgn8/ http://jsfiddle.net/VFgn8/
Have a look at jQuery doc for attr()
. 看看
attr()
jQuery文档 。
The reason is because the replace
method actually returns the new string - not edits it in place. 原因是因为
replace
方法实际上返回了新字符串-不在原地对其进行编辑。
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). 这通过调用函数(第二个参数)为
src
属性设置了一个新值。 This function actiually returns
the replaced value. 该函数实际上
returns
替换值。
Live example (check the src with developer tools): http://jsfiddle.net/4K3Dy/ 实时示例(使用开发人员工具检查src): http : //jsfiddle.net/4K3Dy/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.