我想用find
函數來查找元素,但我怎麼能檢測到沒有發現的東西?如何檢測find()函數未找到任何內容?
這是我的代碼,並不是正常工作,並總是返回true
:
if ($(this).find('img'))
return true;
我想用find
函數來查找元素,但我怎麼能檢測到沒有發現的東西?如何檢測find()函數未找到任何內容?
這是我的代碼,並不是正常工作,並總是返回true
:
if ($(this).find('img'))
return true;
使用.length
if ($(this).find('img').length)
return true;
你需要使用
$(this).find("img").length == 0
即使它可能似乎有點深奧,.find()返回一個jQuery集合對象,它可以繼續ain指向0個或更多DOM元素。您當前的代碼僅檢查是否設置了名爲$(this).find(「img」)的變量。
最好的辦法是使用。長度,例如,如果你的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
}