2011-09-23 93 views
12

可能重複:
Finding whether the element exists in whole html pageisset in jQuery?

我想做出出頭:

HTML

<span id="one">one</span> 
<span id="two">two</span> 
<span id="three">three</span> 

的javascrip牛逼

if (isset($("#one"))){ 
    alert('yes'); 
} 

if (isset($("#two"))){ 
    alert('yes'); 
} 

if (isset($("#three"))){ 
    alert('yes'); 
} 

if (!isset($("#four"))){ 
    alert('no'); 
} 

LIVE:

http://jsfiddle.net/8KYxe/

我怎麼能作出這樣的?

+0

什麼都要被設置爲這些跨度? –

+2

isset是什麼意思? 'span'有一些內容?它存在嗎? –

回答

22
if (($("#one").length > 0)){ 
    alert('yes'); 
} 

if (($("#two").length > 0)){ 
    alert('yes'); 
} 

if (($("#three").length > 0)){ 
    alert('yes'); 
} 

if (($("#four")).length == 0){ 
    alert('no'); 
} 

這是你需要什麼:)

+3

如果沒有找到id,它會拋出錯誤 – Minimihi

+1

'if(!! $('#one')){alert('yes'); } - 等等。這是! JS中沒有雙操作符。 –

8
function isset(element) { 
    return element.length > 0; 
} 

http://jsfiddle.net/8KYxe/1/


,或作爲jQuery的擴展:

$.fn.exists = function() { return this.length > 0; }; 

// later ... 
if ($("#id").exists()) { 
    // do something 
} 
+0

@Tomalak - 感謝編輯:) –

+0

不客氣。 ;) – Tomalak

-2

你可以簡單地使用:

if ($("#one")){ 
    alert('yes'); 
} 

if ($("#two")){ 
    alert('yes'); 
} 

if ($("#three")){ 
    alert('yes'); 
} 

if ($("#four")){ 
    alert('no'); 
} 

對不起,我的錯,它不工作。

+3

'$()'總是返回一個jQuery對象,其值爲'true'。 –

+0

不行,jQuery總是返回jQuery對象。 – Usman

+1

@FelixKling:你最好複製這個評論...也許會有第三個人以這種方式回答......;) –

17

您可以使用length

if($("#one").length) { // 0 == false; >0 == true 
    alert('yes'); 
} 
+3

不需要有> 0,因爲0無論如何都被評估爲false。 –

+0

這表明是否存在具有此ID的elemnt。然而,如果你想知道這個元素是否存在值,你可以做'if($(「#one」)。val()){...}' –

+2

@Richard:對,但是'> 0'是更具表現力,因此更易於閱讀。對於每個人來說,「0」評估爲「錯誤」可能並不是很清楚。 –

-2
function el(id) { 
    return document.getElementById(id); 
} 

if (el('one') || el('two') || el('three')) { 
    alert('yes'); 

} else if (el('four')) { 
    alert('no'); 
}