javascript 如何在没有服务器的情况下使用 HTML 表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6051143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:17:30  来源:igfitidea点击:

How to use HTML forms without a server

javascripthtmlformsparameter-passing

提问by slimbo

I am not a web-developer and want to understand the better way to pass variables. In the past I have used various ways to pass things to java script functions. I have never used forms as I always associated them with server and databases. I have a website in which user selections change the contents of the website.

我不是网络开发人员,想了解传递变量的更好方法。过去,我使用各种方法将东西传递给 java 脚本函数。我从未使用过表单,因为我总是将它们与服务器和数据库相关联。我有一个网站,其中用户的选择会更改网站的内容。

I am wondering if you can use forms without any server just as a way to pass a few things to a javascript function where they are used to change the page content. For basic example, if someone selects male the page background becomes blue, if they choose female the background becomes pink. Would forms be the way to go and just onsubmit call a javascript function? How would I actually pass the form contents to the javascript function?

我想知道您是否可以在没有任何服务器的情况下使用表单作为将一些东西传递给用于更改页面内容的 javascript 函数的一种方式。例如,如果有人选择男性,页面背景变为蓝色,如果他们选择女性,则背景变为粉红色。表单是要走的路,只是在提交时调用 javascript 函数?我实际上如何将表单内容传递给 javascript 函数?

回答by James

Yes you absolutely can use forms/inputs/any kind of html element and never talk to a server, just don't expect to store that data! You're right about using events (like the onsubmit one you mentioned) to trigger Javascript functions.

是的,您绝对可以使用表单/输入/任何类型的 html 元素并且从不与服务器通信,只是不要期望存储该数据!使用事件(如您提到的 onsubmit 事件)来触发 Javascript 函数是正确的。

Here is a quick and dirty example (heavy on the dirty) that does sorta kinda what you'd like. Note that instead of waiting for the form to be submitted before the color change, I go ahead and do it immediately after they choose a gender from the dropdown.

这是一个快速而肮脏的例子(肮脏的东西很重),它有点像你想要的。请注意,我没有在颜色更改之前等待提交表单,而是在他们从下拉列表中选择性别后立即执行此操作。

http://jsfiddle.net/wG8K4/1/

http://jsfiddle.net/wG8K4/1/

回答by Cynthia

You wouldn't pass the parameters. You could have "onsubmit" call a javascript function, and then within the function use javascript to access the actual controls that the user has selected. You could use the GetElementById function to retrieve a certain element, and then determine the value of that element.

你不会传递参数。您可以让“onsubmit”调用 javascript 函数,然后在该函数内使用 javascript 访问用户选择的实际控件。您可以使用 GetElementById 函数检索某个元素,然后确定该元素的值。

If all you wanted to do was change the background color, you could use javascript to change the backgroundColor property of the body tag or any tag on the page.

如果您只想更改背景颜色,则可以使用 javascript 更改 body 标签或页面上任何标签的 backgroundColor 属性。

You'd have to remember to return false from your function, though -- otherwise, the form would be submitted.

但是,您必须记住从函数中返回 false —— 否则,表单将被提交。

回答by Jage

You don't need servers / databases to use forms. Forms are simply a method from passing variables from one file to another, regardless if that is an html file or some php script or what have you. If you stick to using GET forms, your form will naturally pack its data into the URL of your page at which time you can access them. For instance (borrowed from http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/):

您不需要服务器/数据库来使用表单。表单只是一种将变量从一个文件传递到另一个文件的方法,无论它是一个 html 文件还是某个 php 脚本或你有什么。如果您坚持使用 GET 表单,您的表单将自然地将其数据打包到您可以访问它们的页面 URL 中。例如(从http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/借用):

<script language="javascript">
function $_GET(q,s) {
    s = s ? s : window.location.search;
    var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
    return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
} 

var usersName = $_GET('username');
if(typeof(usersName)!='undefined'){
    document.write('<h1>Hi there, '+usersName+'</h1>');
}

</script>
<form>
     <input type="text" name="username" />
     <input type="submit" value="Say my name" />
</form>

回答by sdleihssirhc

The basic event you're going to look for is the form's submitevent. If you're okay with just using event handlers, you can just do something like this:

您要查找的基本事件是表单的submit事件。如果你只使用事件处理程序没问题,你可以做这样的事情:

var myForm = document.getElementById('myForm');
myForm.onsubmit = function () {
    // ...
};

Because you're just using JavaScript, you don't want the form to actually submit. (Side point: Because you're using JS, you should just build this form and add it to the page withJS, but that's a completely different issue.) You can cancel the form's default action like so:

因为您只是在使用 JavaScript,所以您不希望表单实际提交。(边点:由于您使用的JS,你应该建立这个表格,并把它添加到页面JS,但这是一个完全不同的问题。)你可以取消表单的默认操作,如下所示:

myForm.onsubmit = function () {
    // ...
    return false;
};

Before we get into accessing data, make sure that you grab the elements you're going to need. It makes things a little faster, because you don't have to select the entire element from the DOM every time the form is submitted. For example:

在我们开始访问数据之前,请确保您获取了您将需要的元素。它使事情变快了一点,因为您不必每次提交表单时都从 DOM 中选择整个元素。例如:

var myForm = document.getElementById('myForm'),
    myTextField = document.getElementById('myTextField'),
    mySelectBox = document.getElementById('mySelectBox'),
    // ...

Depending on what kind of form elements you have, there are different ways to access their data. Text inputs, text areas, and select boxes are really easy:

根据您拥有的表单元素类型,有不同的方式来访问它们的数据。文本输入、文本区域和选择框非常简单:

var textValue = myTextField.value,
    selectValue = mySelectBox.value;

Radio buttons and check boxes are a little more complicated, because you have to go through every single one and see which one(s) is/are checked and which one(s) isn't/aren't, like so:

单选按钮和复选框稍微复杂一些,因为您必须逐一检查并查看哪些是/已选中,哪些不是/未选中,如下所示:

var isOneChecked = checkboxOne.checked,
    isTwoChecked = checkboxTwo.checked;

Going with your example of blue/pink background, you would probably want something similar to this:

与您的蓝色/粉红色背景示例一起使用,您可能需要类似于以下内容的内容:

var myForm = document.getElementById('myForm'),
    maleBox = document.getElementById('maleBox');

myForm.onsubmit = function () {
    var isMale = maleBox.checked;
    if (isMale) {
        document.body.style.backgroundColor = 'manlyBlue';
    } else {
        document.body.style.backgroundColor = 'sexistPink';
    }
};

Notes
If you dodecide to go with event handlers, keep in mind that only one can be applied to your form at a time. If you want to attach a different function to the submitevent as well, you'll have to go with event listeners, which is a completely different ball game and introduces problems of its own.

注意
如果决定去与事件处理程序,请记住唯一一个可以同时适用于表单。如果您还想为submit事件附加不同的功能,则必须使用事件侦听器,这是一个完全不同的球类游戏,并且会引入其自身的问题。

The final example only checks the value of the "I'm a guy" element, because (presumably) you're using radio buttons and you only have two options. If "I'm a guy" is not checked, then the other one should be. But if the form starts out with neitheroption checked, then that could be considered a bug.

最后一个示例只检查“I'm a guy”元素的值,因为(大概)您正在使用单选按钮并且您只有两个选项。如果“我是男人”没有被选中,那么另一个应该是。但是如果表单开始时没有选中任何一个选项,那么这可能被认为是一个错误。

The final example also uses inline styles to change the body's background color. It hurt me to type. A much more bearable method would be to add/remove classes as needed, but again, that's kind of beyond the scope of this question.

最后一个示例还使用内联样式来更改正文的背景颜色。打字让我很痛苦。一种更可忍受的方法是根据需要添加/删除类,但同样,这超出了这个问题的范围。

回答by mVChr

If your desire is to iterate through form elements using Javascript you can easily do this using the DOM since the form will have a lengthproperty and each inputwill be represented as an index of this array-like object:

如果您希望使用 Javascript 遍历表单元素,您可以使用 DOM 轻松完成此操作,因为表单将具有一个length属性,并且每个属性都input将表示为这个类似数组的对象的索引:

So for:

因此对于:

<form id="f" action="">
    Male<input type="radio" name="gender" value="male" />
    Female<input type="radio" name="gender" value="female" />
    <input type="submit" value="submit" />
</form>

You could do something like this:

你可以这样做:

var f = document.getElementById('f');

f.onsubmit = function (e) {
    e = e || window.event;
    var et = e.target || e.srcElement,
        gender;

    if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }

    for (var i = 0, il = et.length; i < il; i++) {
        if (et[i].name = 'gender' && et[i].checked) {
            gender = et[i].value;
        }
    }

    if (gender == 'male') {
        document.body.style.backgroundColor = 'cyan';
    } else if (gender) {
        document.body.style.backgroundColor = 'pink';
    }
};

See example →

参见示例 →

回答by Oded

Form elements can be used as a form of global variables - holding state that can be used and shared by all the javascript in a single page.

表单元素可以用作全局变量的一种形式 - 保存可以由单个页面中的所有 javascript 使用和共享的状态。

However, this could result in brittle and difficult to understand code.

但是,这可能会导致代码脆弱且难以理解。

I suggest keeping with passing parameters to functions, so long as you are in the context of a single page.

我建议保持将参数传递给函数,只要您处于单个页面的上下文中。

If you need to pass data to another page, then forms can make life easier - using a GETform, the values on the form will be passed to the page referenced in the form actionattribute as key-value pairs. If you use the POSTmethod they will be transferred in the headers.

如果您需要将数据传递到另一个页面,那么表单可以使生活更轻松 - 使用GET表单,表单上的值将action作为键值对传递到表单属性中引用的页面。如果您使用该POST方法,它们将在标题中传输。