通常在JavaScript中我做類似下面的驗證元素確實存在:如何使用jQuery驗證DOM中是否存在元素?
if (document.getElementById('lblUpdateStatus')) {
$("#lblUpdateStatus").text("");
}
但是,使用jQuery - 我該怎麼做同一類型的東西嗎?
通常在JavaScript中我做類似下面的驗證元素確實存在:如何使用jQuery驗證DOM中是否存在元素?
if (document.getElementById('lblUpdateStatus')) {
$("#lblUpdateStatus").text("");
}
但是,使用jQuery - 我該怎麼做同一類型的東西嗎?
get方法返回匹配的DOM元素:
if($("#lblUpdateStatus").get(0)){
$("#lblUpdateStatus").click(function() { ... });
}
但我不確定它是否是一種快速方法。
的事情是,如果該元素存在:-)了jQuery只會做請求的動作, 所以你只需要:
$("#lblUpdateStatus").text("");
$
返回匹配元素的數組,因此檢查length屬性你是好去
if ($('#lblUpdateStatus').length) {
$("#lblUpdateStatus").text("");
}
我沒有理由爲了它而使用jQuery。 $('#lblUpdateStatus')
將基本上直接到document.getElementById('lblUpdateStatus')
,因爲選擇器有一個錨點,所以你沒有真正獲得任何東西。另外,爲了檢查DOM對象是否存在,將它包裝在一個jQuery對象中會產生很多開銷。另一方面,如果只是改變對象的文本屬性就是你想要做的事情,如果你使用jQuery,你不需要檢查它的存在。
if (document.getElementById('lblUpdateStatus')) {
$("#lblUpdateStatus").text("");
}
會做同樣的事情具有隻是
$("#lblUpdateStatus").text("");
的document.getElementById('lblUpdateStatus ')也讀得更好。 – Kieran 2012-07-27 07:09:21
它比你說的要快得多http://jsperf.com/test-dom-selector – Kieran 2012-07-27 07:15:23
@Kieran:`document.getElementById('lblUpdateStatus')`可能更容易閱讀(我不這麼認爲,但我猜測這是一個習慣問題),但如果你試圖用任何聲明返回的東西來做某件事,並且頁面上沒有這樣的元素,那麼你冒着陷入空引用錯誤的風險。在這種情況下,jQuery方法只會默默無聞(這可能或可能不是OP的目標......) – 2012-07-29 15:36:16
我寫了一篇有關該職位上my blog
if ($('#element_id').length > 0)
console.log('the element with element_id exists in the DOM');
如果HTML字符串可以傳遞到$()
,您可以使用parent.length
:
$('<div>').length // 1, but it not exist on page
但
$('<div>').parent().length // 0
從jQuery的1.4起,可以使用$.contains()
。
var test = $("<div>");
$.contains(window.document, test[0]); // false
$("body").append(test);
$.contains(window.document, test[0]); // true
杜佩:http://stackoverflow.com/questions/950563/how-to-find-detect-any-textarea-in-page-using-jquery/950574#950574 – karim79 2009-06-22 13:11:07