简体   繁体   中英

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

thx

Placing the ! at the start negates the $('img...') not the whole expression. 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.

Change

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

To

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

It's due to "src" being undefined. 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/

@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 ''.

better will be to use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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