簡體   English   中英

jQuery檢測不存在的元素

[英]jQuery detecting non-existent element

我有一個函數檢查img標簽是否在一個帶有“colorbox”類的figure元素內,如果是,則為一些元素添加一些額外的樣式。 但是,即使彩盒圖中沒有圖像,該功能仍然可以運行,我不知道為什么。

我的jQuery看起來像這樣

jQuery(document).ready(function($){
  if ($(".colorbox").has("img")) {
     ~code here~
  }
}

這里是彩盒圖,顯然沒有img元素......

<figure class="colorbox">
  <ficaption>
    <h2></h2>
    <p></p>
    <p></p>
  </figcaption>
</figure>

那么為什么jQuery會選擇一個不存在的元素呢?

我更喜歡find功能

var $img = $(".colorbox").find("img");

if ($img.length) { //exisst

}

我會這樣做:

jQuery(document).ready(function($){
  $('.colorbox img').each(function(){
      var imageElement = $(this);
      // do whatever you want with this element !
  });
  // OR this way
  $('.colorbox').each(function(){
      var box = $(this);
      if( box.find('img').length ){
          // this means the parent colorBox has at least 1 img-Element 
      }

  });
}

現在你的問題:

$(".colorbox").has("images");

$(".colorbox")返回元素列表 (如果有)

然后你問列表.has("img") 這意味着如果列表中的一個元素內部有一個img元素,那么由於該if語句而得到一個true ,這就是為什么你的代碼不能按預期工作的原因

已返回新的jquery子集。 你想要if($(".colorbox").has("img").length)檢查那里是否有任何img標簽

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM