jQuerys prop()方法返回错误的id

duc*_*cci 3 forms jquery input prop

当我在表单中输入name ="id"时,prop('id')方法返回输入元素而不是id作为字符串:

HTML

<form id="testform">
    <input name="id">
</form>
Run Code Online (Sandbox Code Playgroud)

JS

var $form = $('#testform');

var wrongId = $form.prop('id');
var correctId = $form.attr('id');

alert(wrongId); // alerts the html input element
alert(correctId); // alerts the id testform
Run Code Online (Sandbox Code Playgroud)

任何人都可以向我解释这个吗?

我准备了一个小提琴:https: //jsfiddle.net/zosu17se/

谢谢,最好

ade*_*neo 5

这是因为您已命名输入id,并且输入的名称或ID,选择和其他"表单元素"作为表单的属性附加到父表单以便于访问,因此form.id是输入,而不是元素id.

千万不能命名输入id或可能需要访问任何其他财产,问题就解决了.

由此引起的奇怪代码示例

var form = window.test; // note that element ID's are also attached to the global scope

form.id.value = 'test';
form.value.value = 'test more';
form.selectedIndex.value = '2';
Run Code Online (Sandbox Code Playgroud)
<form id="test">
  <input name="id">
  <input name="value">
  
  <select id="selectedIndex">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
</form>
Run Code Online (Sandbox Code Playgroud)