我正尝试使用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>
有帮助吗?

解决方案

你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.

其他提示

var text = document.getElementById(namebox).value;

您可能不希望使用document.write为this--使用document.createElement('marquee')创建元素,然后将其添加到页面的主体。您可以设置像你回来的元素属性的方向,其innerHTML设为您的字幕所需的文本。

(P.S。选取框?真的?)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top