【问题标题】:How detect that find() function didn't find anything?如何检测 find() 函数没有找到任何东西?
【发布时间】:2025-12-31 10:20:22
【问题描述】:

我想使用find 函数来查找元素,但我如何检测到没有找到任何东西?

这是我的代码不能正常工作,总是返回true

if ($(this).find('img'))
    return true;

【问题讨论】:

    标签: jquery find


    【解决方案1】:

    使用.length

    if ($(this).find('img').length)
        return true;
    

    【讨论】:

      【解决方案2】:

      最好的方法是使用 .length,例如,如果你的 html 是:

      <div>
        <img src="" alt="" />
      </div>
      

      你的 js/jquery 是:

      var test = $('div').find('img').length;
      alert(test);
      

      有一个包含一张图片的 div,测试会提醒 1。

      在你的情况下:

      if($(this).find("img").length == 0){
      
      // There is no image inside your selected element - Do something
      
      }else{
      
      // There is some image inside your selected element - Do something
      
      }
      

      【讨论】:

        【解决方案3】:

        你需要使用

        $(this).find("img").length == 0
        

        尽管看起来有点深奥,.find() 返回一个 jQuery 集合对象,它可以包含指向 0 个或更多 DOM 元素的指针。您当前的代码仅检查是否设置了名为 $(this).find("img") 的变量。

        【讨论】:

          最近更新 更多