jQuery $(“img ”)。attr(’src’,’new_src’); 不起作用

我的代码不起作用我不知道为什么the_image_source和new_src只是占位符我已经在其中放置了实际值

我也试过$("img[src=the_image_souce]")[0].attr('src','new_src'); 但它也不起作用,请帮忙

您必须通过访问jQuery Object中的[0]元素来了解这将返回DOM元素。 您不能直接在DOM元素上使用jQuery attr()方法。 它必须在jQuery对象上运行

基本上,如果你有多个匹配以下选择器的元素,并且你想访问第一个匹配的元素$("img[src='http://domain.com/image.jpg]")那么你应该使用.first()或.eq() 。 例

 $("img[src='http://sofzh.miximages.com/jquery/image.jpg']").first().attr('src','http://sofzh.miximages.com/jquery/newimage.jpg') 

要么

 $("img[src='http://sofzh.miximages.com/jquery/image.jpg']").eq(0).attr('src','http://sofzh.miximages.com/jquery/newimage.jpg') 

要么

 $($("img[src='http://sofzh.miximages.com/jquery/image.jpg']")[0]).attr('src','http://sofzh.miximages.com/jquery/newimage.jpg'); 

但这看起来很奇怪

好的,浏览器和jQuery版本是什么? 什么不起作用,选择器,设置属性或引导新图像? 从简单开始,alert($(“img [src = imgsrc])]向你展示了什么?在该代码运行之后,firebugs在DOM中说的是什么?

不是没有,但属性选择器没有正确编写。 "很重要。因此你需要:

 $('img[src="the_image_source"]') 

如果你使用相对路径作为image-src,它取决于浏览器,他将检索什么作为src。 大多数浏览器将返回绝对路径,而不是相对路径,因此您的匹配失败。

你只能比较src的结尾:

 $("img[src$='the_image_source']").attr('src','new_src'); 

但是如果在不同目录中有更多具有相同文件名的图像,则可能会导致意外结果。 我认为最好的方法是使用始终包含绝对路径的协议和域作为img-src和jQuery-selectors。

我会做WaldenL建议的并逐一分解,以找出究竟什么不起作用。 首先检查您的选择器。

 alert($("img[src=the_image_source]").length); 

如果大于零,那么你的选择器就好了。 如果没有,那么尝试使用标签的id(如果你知道的话)或获得该图像标签的其他方式。

如果选择器是好的,那么设置src属性有问题。 确保new_src的值是有效的,并且你没有做一些愚蠢的事情,比如在你的变量或拼写错误中添加引号,如下所示:

 var the_image_source = "http://sofzh.miximages.com/jquery/img01.gif"; var new_src = "http://sofzh.miximages.com/jquery/img02.gif"; $('img[src=the_image_souce]').attr('src','new_src'); // won't work - first variable is missing the "r" and not formatted correctly and attr setter has parenthesis $('img[src=' + the_image_source + ']').attr('src',new_src); // should work 

另外,请确保将其放在文档就绪function中。

 $(document).ready(function() { var the_image_source = "http://sofzh.miximages.com/jquery/img01.gif"; var new_src = "http://sofzh.miximages.com/jquery/img02.gif"; $('img[src=' + the_image_source + ']').attr('src',new_src); });