簡體   English   中英

定義對窗口加載的動作

[英]Defining action on window load

我正在嘗試獲取一個頁面來顯示特定屬性,具體取決於是否設置了特定的Cookie。

var x = readCookie('age');
window.onload=function(){
    if (x='null')  {    
        document.getElementById('wtf').innerHTML = ""; 
    };
    if (x='over13')  {    
        document.getElementById('wtf').innerHTML = ""; 
    };
    if (x='not13')  {    
        document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>"; 
    };
}

它總是默認為第一個if語句中的默認值...我仍在學習我的javaScript,所以我確定這是草率的..有人可以幫我解決這個問題嗎?

在Javascript中, =賦值運算符(它將左側的變量設置為右側的值)。 您需要== ,這是寬松的相等運算符(盡管對於您給出的實際示例,您也可以使用=== ,這是嚴格的相等運算符)。

對於這種特定情況,您可能還考慮使用switch

var x = readCookie('age');
window.onload = function(){

    switch (x)
    {
        case null: // Or 'null' if you really meant the string 'null', but I suspect you meant null (not as a string)
            document.getElementById('wtf').innerHTML = "";
            break;
        case 'over13':
            document.getElementById('wtf').innerHTML = "";
            break;
        case 'not13':
            document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
            break;
    }
}

(您可能還想處理價值不屬於您期望的三件事之一的情況。)

var x = readCookie('age');
window.onload=function(){
    if (x==='null')  {    
        document.getElementById('wtf').innerHTML = ""; 
    };
    if (x==='over13')  {    
        document.getElementById('wtf').innerHTML = ""; 
    };
    if (x==='not13')  {    
        document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>"; 
    };

}

這應該是

if (x=='null')  {    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM