如果有一个名为“”的子输入,我如何获得form.method属性值;方法”;

How do I get form.method property value if there is a child input named "method"?

本文关键字:form 何获得 method 属性 方法 有一个 输入 如果      更新时间:2023-09-26

我刚刚发现我可以使用$('form').prop(name)在表单中获得该名称的输入。然后我在其他标签上进行了实验,但这对divbody不起作用。现在,如果有一个名为method的输入,我无法判断表单是否需要postget,不幸的是,在我的一个页面中这是真的。

额外的好处:如果表单中有一个名为action的输入,我也无法获得它的action

<!doctype html>
<html lang="en">
<head>
    <title>jQuery.prop()</title>
    <script src="../../jquery-1.9.1.js"></script>
    <script>
    $(function() {
        var method = $('form').prop('method');
        console.log(method); // <select> element
        var form = $('form')[0];
        console.log(form.method); // <select> element
        $('form').prop('method', 'get');
        console.log(form.method); // still <select> element, but DOM inspector shows the form method is changed to "get"
        form.method='get';
        console.log(form.method); // still <select> element
    });
    </script>
</head>
<body>
    <form action="/Test/Create" method="post">
        <input type="text" name="content" value="" />
        <select name="method">
            <option value="phone">Phone</option>
            <option value="email">Email</option>
        </select>
    </form>
</body>
</html>

那么,当有一个带有该名称的输入时,我如何获得form.method(或action)呢?

如果我理解正确的话,您可以使用jQuery的attr函数。

$('form').attr('action');
$('form').attr('method');

您应该能够在jQuery:上使用.attr

var method = $('#myform').attr('method');
var action = $('#myform').attr('action');
正如其他人所说,属性仍然存在于DOM中。如果你在Page Inspector或类似的工具中打开你的例子,你会发现document.forms[0].attributes在它的映射中有一个"action"和一个"method"键,你可以通过像这样的纯Javascript访问:
document.forms[0].attributes['method'].value

或者通过jQuery这样:

$('form').attr('method');