2010-03-18 37 views
1

我想用JavaScript來啓動一個選框,當用戶把他們的名字放入一個文本框然後點擊一個按鈕。我已經知道如何去做,但我的腳本從未完全正常工作。任何幫助表示讚賞!如何根據用戶輸入使用JavaScript啓動選取框?

這是我到目前爲止有:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title></title> 
<script type="text/javascript"> 
    function StartMarquee() { 
     var text = document.getElementById(namebox); 
     if (text != null) { 
      document.write("<marquee behavior='scroll' direction='right'>Hello " + text + "!</marquee>"); 
     } 
     else { 
      alert("Enter your name first!!!"); 
     } 
    } 
</script> 
</head> 
<body> 
<table style="margin:0px auto 0px auto;"> 
<tr><td>Enter your name!</td> 
<td><input type="text" id="namebox"/></td> 
<td><input type="button" value="Enter" onclick="StartMarquee()"/></td></tr> 
</table> 
</body> 
</html> 
+0

「永不完全有效」是什麼意思? – 2010-03-18 01:25:44

+0

永不完全的作品意味着它會吐出一條提示消息,提示「先輸入用戶名!」或者它會播放一個說「Hello null!」的選取框。 – 2010-03-18 01:31:54

回答

4

您的JavaScript有幾個問題。

  1. 您正在傳遞未定義變量nameboxgetElementById。你需要把它放在引號中('namebox')。
  2. 您需要針對空字符串檢查text的值,而不是null
  3. 您需要在要創建的元素中使用輸入值(text.value而不僅僅是text)。

這裏是你的代碼是什麼樣子與這些修正:

function StartMarquee() { 
    var text = document.getElementById('namebox'); 
    if (text.value !== '') { 
    document.write("<marquee behavior='scroll' direction='right'>Hello " + text.value + "!</marquee>"); 
    } 
    else { 
    alert("Enter your name first!!!"); 
    } 
} 

其他一些一般性的建議:

  1. 不要使用document.write。相反,使用DOM方法創建一個新元素並將其插入到DOM中。
  2. 使用不顯眼的JavaScript。在文檔加載之後附加您的行爲,而不是使用內聯事件處理程序。
  3. 使用===!==來避免類型強制,並確保您獲得您認爲自己的結果。
  4. 永遠不會使用marquee
+0

+1永遠不會使用選取框。 – TiansHUo 2010-03-18 02:22:16

1
var text = document.getElementById(namebox).value; 
+0

P.請閱讀有關不顯眼的JavaScript。 – 2010-03-18 01:30:34

1

你可能不希望使用document.write爲this--使用document.createElement('marquee')創建元素,然後將其添加到的身體頁。您可以在返回的元素上設置方向等屬性,並將其innerHTML設置爲您在選取框中所需的文本。

(P.S. Marquee?真的嗎?)

+0

亞嚴重!選取框? – 2010-03-18 01:29:56

+0

是的,真的。 Marquees也不是我最喜歡的,但我正在與我的一位朋友進行比賽。 – 2010-03-18 01:37:13

+0

@APShredder:比賽。好。 – 2010-03-18 01:38:52

相關問題