jQuery prop() 方法 returns 错误的 id

jQuerys prop() method returns wrong id

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

HTML

<form id="testform">
    <input name="id">
</form>

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

谁能给我解释一下?

我准备了一份fiddle: https://jsfiddle.net/zosu17se/

谢谢,最好的

这是因为您已将输入命名为 id,输入、选择和其他 "form elements" 的名称或 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';
<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>