【问题标题】:jQuerys prop() method returns wrong idjQuery prop() 方法返回错误的 id
【发布时间】:2016-11-17 22:31:27
【问题描述】:
当我在表单中输入 name="id" 时,prop('id') 方法将输入元素而不是 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
谁能给我解释一下?
我准备了一个小提琴:
https://jsfiddle.net/zosu17se/
谢谢,最好的
【问题讨论】:
标签:
jquery
forms
input
prop
【解决方案1】:
这是因为您已将输入命名为 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';
<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>