繁体   English   中英

我正在尝试在文本区域中进行特定的输入,调用特定的javascript函数,但是它将无法正常工作

[英]I'm trying to make a specific input into a text area call a specific javascript function, but it won't work

因此,为了提供一些细节,我正在尝试制作交互式小说游戏或文字冒险。 我有一个表格,其中将键入游戏的所有“命令”。 我正在处理第一个命令,它是字符串“ start”以调用提示。 只是为了测试代码,我迅速提示“成功!” 正确完成时。 但是,发生的是,一旦我打开Web浏览器进行测试,提示就会在我键入命令之前触发。 这是代码。

<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>

<body>

<form id="testForm"> <input type="text" name="">

</form>


</body>
</html>

然后是javascript。

var input = document.getElementById("testForm");

if (input = "start") {
    prompt("Success!");
}

您需要像这样检查输入的值

var input = document.getElementById("inputID");
var value = input.value;

该代码将始终直接运行,因为它没有事件处理程序。 您可以添加一个触发它的按钮

document.getElementById('button').addEventListener('click', function () {
  var input = document.getElementById("inputID");

  if (input.value === 'start') {
    // Do something
  }
});

或者,如果您希望在表单提交事件上:

document.getElementById('testForm').addEventListener('submit', function () {
  var input = document.getElementById("inputID");

  if (input.value === 'start') {
    // Do something
  }
});

尝试这个:

<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>
<body>

<form id="testForm"> 
<input type="text" id="myInput">
</form>

<script>
 var myForm = document.getElementById("testForm");// get the form element.
 var myInput = document.getElementById("myInput");// get the input element
 myForm.onsubmit = function() { // when the form is submitted, execute this function.
    if (myInput.value == "start") { // if the value of the input equals 'start', show prompt.
       prompt("Success!");
    }
    return false; //return false, so the form doesn't get submitted.
};
</script>
</body>
</html>

编辑:添加了Submit事件处理程序,该处理程序返回false,因此不会提交表单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM