1

当用户将他们的姓名放入文本框然后单击按钮时,我正在尝试使用 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>
4

3 回答 3

4

你的 JavaScript 有一些问题。

  1. 您正在将未定义的变量传递nameboxgetElementById. 您需要将其放在引号 ( 'namebox') 中。
  2. 您需要检查text空字符串的值,而不是null.
  3. 您需要在您正在创建的元素中使用输入的值(text.value而不是 just 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. 使用===and !==for 条件来避免类型强制并确保你得到你认为的结果。
  4. 永远,永远使用marquee.
于 2010-03-18T01:39:01.800 回答
1
var text = document.getElementById(namebox).value;
于 2010-03-18T01:25:20.313 回答
1

您可能不想为此使用document.write- 用于document.createElement('marquee')创建元素,然后将其添加到页面的正文中。您可以在返回的元素上设置诸如方向之类的属性,并将其设置innerHTML为您想要在选取框中显示的文本。

(PS Marquee?真的吗?)

于 2010-03-18T01:26:29.787 回答