简体   繁体   English

提交没有表单的输入值

[英]Submitting a value of input without form

I'm creating a website game and currently I am struggling with something I will name "dialogue". 我正在创建一个网站游戏,目前正在努力将其命名为“对话”。

Initially I tried to approach this by creating a form element, but clicking enter or submitting it ended up with page refresh, which ruins everything. 最初,我尝试通过创建表单元素来解决此问题,但是单击Enter或提交它最终导致页面刷新,这破坏了一切。

So I used inpute type text without form that looks like this: 因此,我使用了无格式的inpute类型文本,如下所示:

You are 
<input type="text" id="dead">
<input type="submit" onclick="dead()">

and dead function looking currently like this, later it's gonna check for certain value, and if the value is true it's gonna run another code: 和Dead函数当前看起来像这样,稍后将检查某些值,如果该值为true,则将运行另一个代码:

var talk = document.getElementById("dead").value;

function dead() {
alert(talk);
}

And I don't know how to save input from a form so it would be detected by JS and then used as variable in boolean check. 而且我不知道如何保存来自表单的输入,因此它会被JS检测到,然后用作布尔检查中的变量。 How can I solve this problem? 我怎么解决这个问题? If there is a way to use a form tag without refreshing the page that could also work. 如果有一种使用表单标签而不刷新页面的方法,那也可以。

You can handle the submit event of your form like this: 您可以按以下方式处理表单的Submit事件:

document.getElementById('yourFormId').onsubmit = function(e) {
    // your code goes here...

    e.preventDefault(); // this will prevent the default operation of your form within this event
    return false;
}

Or create a function: 或创建一个函数:

function handleForm(e) {
    // your code goes here...

    e.preventDefault();
    return false;
}

And add this to your form tag: 并将其添加到您的表单标签:

<form onsubmit="return handleForm(this);">

To be able sending some value without refresh the page you can use Asynchronous JavaScript + XML (AJAX) and if you're working with pure Javascript without some frameworks you can see a good documentation about Ajax . 为了能够发送一些值而不刷新页面,您可以使用Asynchronous JavaScript + XML(AJAX);如果您使用的是不带某些框架的纯Javascript,则可以查看有关Ajax的优质文档。 But of course I suggest to use some frameworks like Jquery to make your works more easier 但是我当然建议使用某些框架,例如Jquery ,使您的工作更轻松

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

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