2015-05-29 12 views
0

我很困惑,爲什麼這不會工作...使用Javascript - 如果與或聲明 - IE未定義

在Chrome中,當我點擊運行此腳本按鈕,彈出是空的文本框,所以我檢查長度> 0 .....

在IE瀏覽器,它填充爲未定義,所以我想我可能只是檢查值,如果說!=未定義...

if (strTemp.length > 0) { 
    if (strTemp.value != "undefined") { 
     printLabels(strCarrier, strTemp); 
    } else { 
     alert('You wont get labels until you tell us why...'); 
    } 
} 
else { 
    alert('You wont get labels until you tell us why...'); 
} 

任何人有什麼想法我做錯了什麼?

+3

不確定是不是與undefined字符串相同... – lifetimes

+0

undefined不應該是一個字符串 – AkshayJ

+0

使用'if(strTemp.length> 0 && strTemp.value!= undefined)' – maioman

回答

4

如果該值爲undefined,它不是字符串。您應該檢查if (strTemp.value != undefined)

請參閱MDN上的undefined

+2

或使用typeof並與字符串進行比較。 – zozo

+0

完美...謝謝@Scimonster –

+0

所以這似乎沒有工作,因爲現在這套代碼,它不會讓任何事情經過? –

0
if (strTemp && strTemp.value) { 
    printLabels(strCarrier, strTemp); 
} else { 
    alert('You wont get labels until you tell us why...'); 
} 
+0

雖然這段代碼可以解決這個問題,[包括解釋](http:// meta .stackexchange.com/questions/114762/explain-completely-code-based-answers)確實有助於提高帖子的質量。請記住,您正在爲將來的讀者回答問題,而這些人可能不知道原因爲你的代碼建議。 – Scimonster

+0

'if(strTemp && strTemp。值){ printLabels(strCarrier,strTemp); } else { alert('你不會得到標籤,直到你告訴我們爲什麼......'); }' –

+0

也沒有工作在IE –

2

未定義的是數據類型,而不是字符串值。如果你要比較的字符串,請嘗試使用此:

if (typeof strTemp.value === "undefined") { 
    alert("strTemp.val is undefined"); 
} 
+0

'如果((strTemp.length> 0)&&(typeof運算strTemp.value === 「未定義」)){ \t \t \t \t printLabels(strCarrier,strTemp); \t \t \t}其他{ \t \t \t \t警報( '直到你告訴我們,爲什麼你不會得到標籤...'); \t \t \t}' –

+0

工作在chrome中,但不在IE中時,它被設置爲undefined –

0

只是櫃面任何人想知道......這是我怎麼會解決它....

if (strTemp.length > 1) { 
      if ((strTemp == "undefined") || (strTemp == "")){ 
       alert('You wont get labels until you tell us why...'); 
      }else{ 
       printLabels(strCarrier, strTemp); 
      } 
     }else{ 
      if ((strTemp == "undefined") || (strTemp == "")){ 
       alert('You wont get labels until you tell us why...'); 
      }else{ 
       printLabels(strCarrier, strTemp); 
      } 

     }