Javascript 如何将图像src设置为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13726593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:45:15  来源:igfitidea点击:

How to set image src to empty?

javascriptjqueryimage

提问by StackOverflower

Possible Duplicate:
Setting image src attribute not working in Chrome

可能重复:
设置图像 src 属性在 Chrome 中不起作用

When user clicks on "remove" link I need to set the srcattribute of an image to empty. When I do it using

当用户单击“删除”链接时,我需要将src图像的属性设置为空。当我使用

$('#img').prop('src', null);

srcis not empty but points to current url

src不为空但指向当前网址

if I remove srcusing

如果我删除src使用

$('#img').removeProp('src');

never let me to assign it back in the future

永远不要让我将来再分配它

What's the best way to accomplish this?

实现这一目标的最佳方法是什么?

采纳答案by Adil

Try using attr(),

尝试使用attr()

Live Demo

现场演示

$('#img').attr('src', '');

As you have id selector. Using the native javascript method document.getElementById will give you more performance benefit. Also you may need to set #as srcinstead of emptystring.

因为你有 id 选择器。使用原生 javascript 方法 document.getElementById 将为您带来更多的性能优势。此外,您可能需要设置#src而不是empty字符串。

document.getElementById('img').src = "#";

回答by jAndy

I'd just access the underlaying <img>node and set the value of srcto an empty string.

我刚刚访问垫层<img>节点的值设置src空字符串

$('#img')[ 0 ].src = '#';

Fiddle: http://jsfiddle.net/P4pRu/

小提琴:http: //jsfiddle.net/P4pRu/



Update: It seems like Chromeis not satisfied when we just pass in an empty string. Firefox still shows the expected behavior (I'm pretty sure that this also worked in Chrome a couple of weeks/versions ago).

更新:当我们只传入一个空字符串时,Chrome似乎并不满意。Firefox 仍然显示预期的行为(我很确定这在几周/几个版本前在 Chrome 中也有效)。

However, passing over a #for instance, works fine.

但是,传递一个#例如,工作正常。



Update 2:

更新 2:

Even imgNode.removeAttribute('src');does no longer remove the visual representation of an image anymore in Chrome (interesting...).

甚至imgNode.removeAttribute('src');不再在 Chrome 中删除图像的视觉表示(有趣......)。

回答by Jay Blanchard

The attribute 'src' isn't really a property, it is an attribute. Think of properties as things that can be set with booleans or lists and attributes as things that are much more dynamic.

属性 'src' 并不是真正的属性,它是一个属性。将属性视为可以使用布尔值或列表设置的事物,而将属性视为更加动态的事物。

$('#img').attr('src', '');

As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes - http://api.jquery.com/prop/

从 jQuery 1.6 开始, .prop() 方法提供了一种显式检索属性值的方法,而 .attr() 检索属性 - http://api.jquery.com/prop/