Html 用于名称和值的表单中的 Javascript foreach 输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15869897/
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-08-29 07:20:15  来源:igfitidea点击:

Javascript foreach input in form for Name and Value

javascripthtmlformsforeach

提问by Moussa Harajli

I am just practicing some javascript and i used to use JQuery a lot! I have had no major experience with raw javascript and i want to learn it just as i did JQuery. I have a simple form and a javascript function to go with it onsubmit and i want to get the name and value of each input in the form with my function but it doesnt seem to work can someone help me out?

我只是在练习一些 javascript,我曾经经常使用 JQuery!我没有使用原始 javascript 的主要经验,我想像学习 JQuery 一样学习它。我有一个简单的表单和一个 javascript 函数来配合它提交,我想用我的函数获取表单中每个输入的名称和值,但它似乎不起作用有人可以帮助我吗?

<!DOCTYPE html>
<html>
<head>
    <title>Foreach Practice</title>
    <script type="text/javascript">
        function Get() {
            var Form = document.getElementById('Form');
            for(I = 0; I < Form.length; I++) {
                var Value = this.attribute('name').value;
                alert(Value);
            }
        }
    </script>
</head>
<body>
<form id="Form" onsubmit="return false;">
    <input type="text" name="User" placeholder="Username" />
    <input type="password" name="User" placeholder="Password" />
    <input type="submit" name="Submit" onclick="javascript:Get();" />
</form>
</body>
</html>

回答by RobG

This question is probably better suited to code review, but whatever.

这个问题可能更适合代码,但无论如何。

> function Get() {

Variable names starting with a capital letter are, by convention, reserved for constructors. Also, names should indicate what the function does, a generic "get" function doesn't give much of a hint. A better name might be getFormValues.

按照惯例,以大写字母开头的变量名是为构造函数保留的。此外,名称应该表明函数的作用,通用的“get”函数不会给出太多提示。更好的名称可能是getFormValues

>     var Form = document.getElementById('Form');

There is a document.formscollection available that can be used as an alternative to calling a method:

有一个document.forms集合可用作调用方法的替代方法:

    var form = document.forms('Form');

>     for(I = 0; I < Form.length; I++) {

You should always declare variables in an appropriate scope (noting that ECMAScript only has global, function and eval scope, there is no block scope), especially counters. Also, the form's lengthattribute is the number of controls in the form. Since it's a live collection, getting the length every time when you don't need to is potentially a performance hit, so cache the value:

您应该始终在适当的范围内声明变量(注意 ECMAScript 只有全局、函数和 eval 范围,没有块范围),尤其是计数器。此外,表单的长度属性是表单中控件的数量。由于它是一个实时集合,因此每次不需要时获取长度可能会影响性能,因此缓存该值:

    for (var i = 0, iLen = form.length; i < iLen; i++) {

>         var Value = this.attribute('name').value;

The value of thisis set by how you call a function. If the function is called by a handler, then depending on the browser and method attachment, thiswill reference the element whose listener called the function. In this case, because the function is called by an inline listener, thishas not been set so will default to the global object.

this的值由您调用函数的方式设置。如果该函数由处理程序调用,则取决于浏览器和方法附件,将引用其侦听器调用该函数的元素。在这种情况下,因为该功能是通过内嵌侦听器调用,还没有被设置成默认为全局对象。

You can easily pass a reference to the element from the listener if you do:

如果您这样做,您可以轻松地从侦听器传递对元素的引用:

<input ... onclick="getFormValues(this);" ... >

Now your function will receive a reference to the element and can conveniently get a reference to the form and iterate over the controls. Finally, it is rare to need to access a form control's attribute values, you nearly always want to access properties. So here's the re-written function:

现在您的函数将接收对元素的引用,并且可以方便地获取对表单的引用并遍历控件。最后,很少需要访问表单控件的属性值,您几乎总是想要访问属性。所以这是重写的函数:

function getFormValues(element) {
    var form = element.form;
    var controls = form.controls;

    for (var i=0, iLen=controls.length; i<iLen; i++) {
        alert(controls[i].name + ': ' + controls[i].value);
    }
    // Prevent form submission
    return false;
}

Lastly, you are better to call the listener from the form rather than the submit button, since forms can be submitted by means other than clicking a submit button. Oh, and don't call any form control "submit" or use any name that is the same as a form method as it will overwrite the same–named method. You get away with it here due to capitalisation, but that is not much defense.

最后,最好从表单而不是提交按钮调用侦听器,因为可以通过单击提交按钮以外的方式提交表单。哦,不要调用任何表单控件“提交”或使用任何与表单方法相同的名称,因为它会覆盖同名方法。由于大写,您可以在这里逃脱,但这并不是防御。

The related HTML can be (note that the form now doesn't need either a name or id):

相关的 HTML 可以是(请注意,表单现在不需要名称或 ID):

<form onsubmit="return getFormValues();">
    <input type="text" name="userName" placeholder="Username">
    <input type="password" name="userPassword" placeholder="Password">
    <input type="submit" name="submitButton">
</form>

回答by Iswanto San

You should iterate to form's childrenand use getAttributefunction to get attribute value.

您应该迭代表单的子项并使用getAttribute函数来获取属性值。

Try this:

尝试这个:

function Get() {
    var Form = document.getElementById('Form');         
    var childs = Form.children;         
    for(I = 0; I < childs.length; I++) {                    
        var Value = childs[I].getAttribute('name');                             
        alert(Value);
    }
}

回答by Moussa Harajli

Anyone looking for the answer to this i figured it ou just by using random attempts of rearranging my code but here it is.

任何人都在寻找答案,我只是通过随机尝试重新排列我的代码来发现它,但它就在这里。

<!DOCTYPE html>
<html>
<head>
    <title>Foreach Tutorial</title>
    <script type="text/javascript">
        function Get() {
            var Form = document.getElementById('Form');
            for(I = 0; I < Form.length; I++) {
                var Name = Form[I].getAttribute('name');
                var Value = Form[I].value;
                alert(Name + ' : ' + Value);
            }
        }
    </script>
</head>
<body>
<form id="Form" onsubmit="return false;">
    <input type="text" name="User" placeholder="Username" />
    <input type="password" name="Pass" placeholder="Password" />
    <input type="submit" name="Submit" onclick="Get();" />
</form>
</body>
</html>