【问题标题】:How to Get and Print a String Using HTML如何使用 HTML 获取和打印字符串
【发布时间】:2015-05-03 08:53:15
【问题描述】:

我正在处理一个小项目(处理获取名称并使用字符串打印它)。问题是当我点击按钮时,什么也没有发生。

代码:

<!DOCTYPE html>
<html>
    <head>
        <link type = "css" rel="stylesheet" href = "css.css"/>
        <script>
                var button = document.getElementById('send');
                var enter = document.getElementById('enter');
                    button.onclick function() {
                        var str = 'Hello ' + enter.value + ' how are you?'; 
                    alert(str);
                    }
        </script> 
        <title>HAL 9000 SIM</title>
    </head>
    <body>
        <p id=p1> What is your name? </p>
        <br><br>
        <input type = "text" id="enter" name = "entername"><br>
        <input type = "button" id="send" value="Enter">
</html>

正如您可能知道的那样,它并不完整,因此非常需要任何其他指针!

【问题讨论】:

  • 仔细查看button.onclick 的语法。你错过了什么......
  • 你说你被卡住了......请详细说明,因为你从不描述“手头的问题”......

标签: javascript html integration


【解决方案1】:

您似乎忘记了 button.click 后面的“=”符号。

检查一下:

<body>
    <p id=p1>What is your name?</p>
    <br>
    <br>
    <input type="text" id="enter" name="entername">
    <br>
    <input type="button" id="send" value="Enter">

--

    var button = document.getElementById('send');
    var enter = document.getElementById('enter');
    button.onclick =
    function () {
        if(enter.value.length > 0)
        {   
            var str = 'Hello ' + enter.value + ' how are you?';
            alert(str);
        }else
        {
            alert("Please input the required fields!");
        }
    };

http://jsfiddle.net/pg5k60rz/

【讨论】:

    【解决方案2】:

    首先,你没有指定 onclick 你的函数

    var enter = document.getElementById('enter');
    button.onclick  = function() {
      var str = 'Hello ' + enter.value + ' how are you?'; 
      alert(str);
    }

    其次,如果您希望您的代码工作,但在关闭正文标记之前编写脚本

    【讨论】:

      猜你喜欢
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多