简体   繁体   English

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

[英]Check if img src is empty using jQuery attr

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 谢谢

Placing the ! 放置! at the start negates the $('img...') not the whole expression. 一开始会否定$('img ...')而不是整个表达式。 Try: 尝试:

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

! operator will be evaluated before the result (boolean) returned from == operator and will be applied to object returned by selector instead of boolean returned by == operator. 运算符将在==运算符返回的结果(布尔值)之前进行评估,并将应用于选择器返回的对象,而不是==运算符返回的boolean

Change 更改

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

To

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

It's due to "src" being undefined. 这是由于未定义“ src”。 You should use this (it's more efficient than != ""): 您应该使用它(它比!=“”更有效):

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

You can see this working here: http://jsfiddle.net/GKHvQ/ 您可以在这里查看此工作: http : //jsfiddle.net/GKHvQ/

@adil & @scoot @adil和@scoot

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

this condition says that if attribute src is not blank. 此条件表明,如果属性src不为空。 But the condition would be to check if src attribute is ''. 但条件是检查src属性是否为。

better will be to use 更好的是使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM