简体   繁体   English

如果有一个名为“ method”的子输入,如何获取form.method属性值?

[英]How do I get form.method property value if there is a child input named “method”?

I just found that I can use $('form').prop(name) to get input with that name within the form. 我刚刚发现我可以使用$('form').prop(name)在表单中获取具有该名称的输入。 Then I experimented on other tags, and this won't work for div and body . 然后,我尝试了其他标签,但是这不适用于divbody Now I don't have a way to tell if a form needs to post or get if there is an input named method , which unfortunately is true in one of my pages. 现在,我没有办法判断表单是否需要postget是否有一个名为method的输入,但是不幸的是,在我的页面之一中,这是正确的。

Bonus: I can't get action of a form if there is an input named action inside it, either. 奖金:我不能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>

So, how do I get form.method (or action) when there is an input with that name inside it? 因此,当输入中包含该名称时,如何获取form.method(或动作)?

You could just use jQuery's attr function, if I'm understanding the question correctly. 如果我正确理解了这个问题,则可以只使用jQuery的attr函数。

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

You should be able to use .attr on jQuery: 您应该能够在jQuery上使用.attr

var method = $('#myform').attr('method');
var action = $('#myform').attr('action');

As others have stated, the attribute is still there in the DOM. 正如其他人所说,该属性仍在DOM中。 If you open your example in Page Inspector or a similar tool, you'll find that document.forms[0].attributes has both an "action" and a "method" key in its map, which you can access via plain Javascript like so: 如果您在Page Inspector或类似工具中打开示例,则会发现document.forms [0] .attributes在其映射中同时具有“ action”和“ method”键,您可以通过诸如所以:

document.forms[0].attributes['method'].value

Or via jQuery like so: 或像这样通过jQuery:

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

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

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