我会尽力使我的问题尽可能简单明了。所以我最近读了.prop()
vs .attr()
stackoverflow 上的页面,并决定开始使用 prop()
而不是 attr()
。
HTML
<form action="php/select.php" method="POST" class="ajax">
<fieldset>
<legend>Show</legend>
<div>
<input type="submit" value="Show Servers"/>
</div>
<div id="output"></div>
</fieldset>
<input type="hidden" name="action" value="SHOW_SERVERS"/>
</form>
JQuery
$(document).ready(function(){
$("form.ajax").on("submit",function(e){
e.preventDefault();
var t=$(this);
var form=t.serialize();
var method=t.prop("method");
var url=t.prop("action");//Before: t.attr("action");
console.log(url);
});
});
奇怪的部分来了,当我提交该表单时,它在控制台中打印的是这个
我的问题是:
为什么 JQuery 返回输入元素而不是表单操作属性的值?
为什么.prop()
可以获取到method属性的值,却不能获取到action属性
PS:我已经知道输入具有属性name="action"
。
最佳答案
Why does JQuery return an input element rather than the value of the form action property?
它与 jQuery 本身无关。
它是HTML本身的规范。表单中的控件随表单一起提交,并且控件的名称
成为表单的属性。更多信息请参见:http://www.w3.org/TR/html401/interact/forms.html#control-name
这与 form
标记上的属性不同。
因此,即使不使用 jQuery,如果您要引用名为 example
的 input
元素,您也可以将其作为 formname.example
.
fiddle :https://jsfiddle.net/abhitalks/jct8ksr3/
片段:
$("form.ajax").on("submit",function(e){
e.preventDefault();
console.log(this.example);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="php/select.php" method="POST" class="ajax">
<div>
<input type="text" name="example" value="test"/>
<input type="submit" value="Show Servers"/>
</div>
</form>
jQuery 的作用是用 attr
公开attribute
。这些返回的属性值(标签)实际上不会从源中更改。然而,jQuery 还公开了元素的属性(包含的标签属性的当前值)。由于表单控件名称作为属性附加到表单,因此它也会返回这些名称。
您只需将其记录在代码中就可以看到:
console.log(t);
关于jquery - .prop() 返回对象而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34526069/