我在表单外有一些输入字段。使用HTML5表单属性
<form id="myform">
<input type="text" name="mytext" />
<input type="submit" value="test" />
</form>
<input form="myform" type="hidden" name="extra" id="extra" value="777" />
<select form="myform" name="filter" id="filter">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
并尝试在提交时序列化表格
$('#myform').on('submit', function (e) {
var query = $(this).serialize();
if ($.browser.msie) {
//fixed form attribute not supported in IE
var extra = $('[form=myform]').each(function () {
if (/(=)\w*/gi.test(query)) query += '&';
query += this.name + '=' + this.value;
});
}
console.log(query);
return false;
});
但目前http://api.jquery.com/jquery.browser/说
“此属性已在jQuery 1.9中删除,仅可通过jQuery.migrate插件使用。请尝试使用功能
检测”。
因此,如何检测浏览器支持此表单属性功能?
还是有更好的方法来做到这一点
最佳答案
如果要在不使用外部插件或库的情况下检查form
属性,则可以尝试以下操作:
更改:
if ($.browser.msie) {
至:
if ($("#extra")[0].form === null) {
有关为何使用
$("#extra")[0]
的更多信息,请参见document.getElementById vs jQuery $()。导致:
$('#myform').on('submit', function (e) {
var query = $(this).serialize();
if ($("#extra")[0].form === null) {
//fixed form attribute not supported in IE
var extra = $('[form=myform]').each(function () {
if (/(=)\w*/gi.test(query)) query += '&';
query += this.name + '=' + this.value;
});
}
console.log(query);
return false;
});
JS小提琴:
http://jsfiddle.net/ezq9mu1a/1/
据我所知,这就是Modernizr所做的检查(尽管我认为它是动态创建要测试的输入)。在IE中运行此小提琴会触发后备代码,而Safari,Chrome,Firefox和Opera仅使用
serialize
。编辑
由于我们不能依赖页面中的现有元素,因此我们需要创建测试
form
和input
以便检查是否支持form
属性。为此,我们可以通过以下方式修改代码:加:
//Create test elements and amend them to the DOM
var testForm = $('<form />', { 'id': "testForm" })[0];
var testInput = $('<input />', { 'form': "testForm" })[0];
$('body').append(testForm, testInput);
//Set a variable to store whether the form attribute is supported
var formSupported = (testInput.form !== null) ? true : false;
//Remove the test elements from the DOM
$(testForm).remove();
$(testInput).remove();
更改:
if ($("#extra")[0].form === null) {
至:
if (!formSupported) {
导致:
//Create test elements and amend them to the DOM
var testForm = $('<form />', { 'id': "testForm" })[0];
var testInput = $('<input />', { 'form': "testForm" })[0];
$('body').append(testForm, testInput);
//Set a variable to store whether the form attribute is supported
var formSupported = (testInput.form !== null) ? true : false;
//Remove the test elements from the DOM
$(testForm).remove();
$(testInput).remove();
if (!formSupported) {
$("#formSupported").html("No");
}
$('#myform').on('submit', function (e) {
var query = $(this).serialize();
if (!formSupported) {
//fixed form attribute not supported in IE
var extra = $('[form=myform]').each(function () {
if (/(=)\w*/gi.test(query)) query += '&';
query += this.name + '=' + this.value;
});
}
console.log(query);
return false;
});
JS小提琴:
http://jsfiddle.net/ezq9mu1a/3/
关于jquery - 检测HTML5输入的form属性,如果不支持,请尝试序列化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25479434/