javascript 使用 jQuery attr 检查 img src 是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16011289/
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-10-27 02:55:21  来源:igfitidea点击:

Check if img src is empty using jQuery attr

javascriptjqueryimage

提问by Adam

I'm trying the following code:

我正在尝试以下代码:

            if(!$('img.photoPreview', this).attr('src') == '') {
                    alert('empty src...');
            }

but it errors in the editor as not being completed correctly.

但它在编辑器中出错,因为没有正确完成。

Can someone advise what is wrong?

有人可以建议有什么问题吗?

Note: I'm trying to check - if not this image src is empty...

注意:我正在尝试检查 - 如果不是这个图像 src 是空的......

thx

谢谢

回答by scoota269

Placing the ! at the start negates the $('img...') not the whole expression. Try:

放置!在开始否定 $('img...') 不是整个表达式。尝试:

if ($('img.photoPreview', this).attr('src') != '') {
    alert('empty src');
}

回答by Adil

!operator will be evaluated before the result (boolean) returned from ==operator and will be applied to object returned by selector instead of booleanreturned by ==operator.

!运算符将在运算符返回的结果(布尔值)之前进行评估==,并将应用于选择器返回的对象而不是运算符boolean返回的对象==

Change

改变

if(!$('img.photoPreview', this).attr('src') == '') 

To

if($('img.photoPreview', this).attr('src') != '') 

回答by Chris Dixon

It's due to "src" being undefined. You should use this (it's more efficient than != ""):

这是由于“src”未定义。您应该使用它(它比 != "" 更有效):

if(!$('img.photoPreview', this).attr('src')) {
     alert('empty src...');
}

You can see this working here: http://jsfiddle.net/GKHvQ/

你可以在这里看到这个工作:http: //jsfiddle.net/GKHvQ/

回答by Amit Sharma

@adil & @scoot

@adil & @scoot

if($('img.photoPreview', this).attr('src') != '') 

this condition says that if attribute src is not blank. But the condition would be to check if src attribute is ''.

此条件表示如果属性 src 不为空。但条件是检查 src 属性是否为 ''。

better will be to use

更好的是使用

if($('#photoPreview').attr('src') == '') {
 alert('empty src...');
}