2016-11-29 58 views
0

只有當DOM(img標籤)中的特定元素存在時,我才需要運行一些代碼,如果不存在,那麼我想運行其他代碼。下面是我到現在爲止的內容。如何檢查jQuery中的元素

原始代碼:

ed.on('blur', function (e) { 
     var iFrame = $('iframe'); 

     $("img[src*='blob']", iFrame.contents()).each(function (i) { 
      var originalUrl = $(this).prop('src'); 
      var that = $(this); 
      // SOME CODE 

      ); 
     }); 

下面是我想

ed.on('blur', function (e) { 
    var iFrame = $('iframe'); 
******If (img[src*='blob' exists in the iFrame)******** 
    $("img[src*='blob']", iFrame.contents()).each(function (i) { 
     var originalUrl = $(this).prop('src'); 
     var that = $(this); 
     // SOME CODE 
     ); 
    } 
    else 
    { 
     // Do something else 
    } 
}); 

所以基本上,如果我不能找到我想要運行一些其他的代碼的iframe $("img[src*='blob']"。請指導我。

+1

所以選擇它,並檢查長度.... – epascarello

+1

爲什麼是一個笨蛋? OP正在使用內容作爲上下文選擇器......重複應該是如何檢查一個元素是否存在...... – epascarello

+0

@epascarello:你是什麼意思?我很困惑。所以下面的答案不適用於我的代碼? – Unbreakable

回答

1

因此,而不是隻是在做各,它存儲到一個變量,並檢查長度。

var imgs = $("img[src*='blob']", iFrame.contents()); 
//var imgs = iFrame.contents().find("img[src*='blob']"); //how I would write it 
if (imgs.length) { 
    imgs.each(...) 
} else { 
    ... 
} 
+0

在所有的答案中,只有你的答案奏效。謝謝你,先生。非常感謝您的幫助。 – Unbreakable

0
$("img[src*='blob']").length > 0 
1

你要檢查的jQuery對象(jQuery.length)的元素個數:

if($('img[src*="blob"]').length > 0) { 
    // your code 
} 
+0

此代碼將如何訪問iFrame內容? –