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

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

Check if img src is empty using jQuery

javascriptjqueryhtmlimage

提问by Adam

I have the following HTML:

我有以下 HTML:

 <div class="previewWrapper" id="thumbPreview3">
  <div class="previewContainer">
   <img src="" class="photoPreview" data-width="" data-height=""><span>3</span>
  </div>
 </div>

And I have the following JQUERY which isn't working.

我有以下 JQUERY 不起作用。

    if($('div.previewWrapper div.previewContainer img').attr('src') == '') {
      alert('got me');
    }

can anyone advise what I'm missing. What to get the click event to work when the src is empty.

任何人都可以建议我缺少什么。当 src 为空时如何让点击事件起作用。

thx

谢谢

采纳答案by Alessandro Minoccheri

try this code:

试试这个代码:

$(document).ready(function(){
    if ($("div.previewWrapper div.previewContainer img[src=='']").click(function()){
          alert('got me');
        }
});

回答by Mihai Matei

You should do your verification inside document ready function

您应该在文档就绪功能中进行验证

$(document).ready(function(){
   if($('div.previewWrapper div.previewContainer img').attr('src') == '') { 
      alert('got me'); 
    }
});

回答by Priyank Patel

You should wrap this in document.ready function like this

您应该像这样将其包装在 document.ready 函数中

$(document).ready(function(){

if($('div.previewWrapper div.previewContainer img').attr('src') == '')
     {
      alert('got me');
    }


});

回答by muthu

Please Check this It seems working here

请检查这个它似乎在这里工作

<div class="previewWrapper" id="thumbPreview3">
  <div class="previewContainer">
   <img src="" class="photoPreview" data-width="" data-height=""><span>3</span>
  </div>
</div>
<input type="button" id=click value =" Click me" />


$(function () {

    $("#click").click(function () {

        if ($('div.previewWrapper div.previewContainer img').attr('src') == '') {
            alert('got me');
        }
    });


});?