简体   繁体   English

HTML表单onsubmit传递this.id; 产生意想不到的价值

[英]HTML form onsubmit passing this.id; yielding unexpected value

I'm working on a website and was experiencing this problem, so I simplified it as much as possible. 我正在一个网站上工作,遇到了这个问题,所以我尽可能地简化了它。

index.html: index.html:

<html>
<head></head>
<body>
    <script type="text/javascript" src="test.js"></script>

    <form id="myForm" onsubmit="log(this.id)">
        <input name="id">
    </form>
</body>
</html>

test.js: test.js:

function log(str){
    console.log("str=" + str);
}

When I submit the form, I see this: 提交表单时,我看到以下内容:

str=[object HTMLInputElement] str = [对象HTMLInputElement]

and when I change the value of name to anything but "id", I see the expected 当我将name的值更改为“ id”以外的任何值时,我看到了预期的

str=myForm str = myForm

I get the exact same behavior if I switch all instances of "name" and "id" in the code. 如果在代码中切换“名称”和“ id”的所有实例,则会得到完全相同的行为。 In other words, it doesn't seem to be a particular limitation of either attribute, but something more general. 换句话说,这似乎不是这两个属性的特定限制,而是更通用的东西。

I'm running MAMP on OS X 10.8; 我在OS X 10.8上运行MAMP; experiencing problem in Firefox 22.0 and Chrome ver. 在Firefox 22.0和Chrome版本中遇到问题。 28. 28。

Thanks in advance 提前致谢

The .id on form elements accesses form fields by their name. 表单元素上的.id按其名称访问表单字段。 To get the ID attribute use this.getAttribute('id') . 要获取ID属性,请使用this.getAttribute('id')

When you gave the input the name "id", log(this.id) translates to log(myForm.id) where id is a property of myForm, it is in fact the input child element. 当您为输入提供名称“ id”时,log(this.id)转换为log(myForm.id),其中id是myForm的属性,实际上是输入子元素。 This is indicated by the [object HTMLInputElement] class name which appears. 这由出现的[object HTMLInputElement]类名称指示。

When you name the input child control to something else this.id now refers to the forms id attribute. 当您将输入子控件命名为其他名称时,this.id现在引用了表单id属性。

The same logic applies when you switch "id" with "name" since you can refer to controls by either their name or id. 当您用“名称”切换“ id”时,同样的逻辑适用,因为您可以通过控件的名称或id来引用它们。

Well, that's because this.id is being interpreted as " the element with name id that belongs to the form ", that's why you're receiving an [object HTMLInputElement] through the parameter. 好吧,这是因为this.id被解释为“ 名称id属于形式的元素 ”,这就是为什么您通过参数接收到[object HTMLInputElement]的原因。 When there is no such input (ie when you name it differently), this.id is interpreted as the form id . 如果没有这样的输入(即使用不同的名称),则this.id被解释为id形式

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

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