【发布时间】:2014-07-19 18:47:34
【问题描述】:
我有一个包含两个选项卡的页面,每个选项卡都包含一个表单。表单以相同的方式解析,只是它们被用于不同的 URL/API。
我想使用相同的函数来解析表单,而不是重复相同的函数,所以我在 URL 中获取哈希以获取选项卡编号,然后将其添加到 jquery 目标,请参见下面的代码:
$(document).ready(function () {
$('#tab-container').easytabs();
var tab = '#tab1'; // when index loaded, there is no hash, so I set tab to be #tab1 by default
window.onhashchange= function() {
tab = window.location.hash;
console.log(tab);
};
$(tab + ' form').submit(function(e) {
e.preventDefault(); // Prevents the page from refreshing
var url = $(this).attr('action')
$.ajax({
type: "POST",
url: url,
data: $(tab + ' form').serialize(), // serializes the form's elements.
success: function(data)
{
var result = JSON.parse(data);
// check to see if there are more than one value in the response. values are separated by commas
if (result.response.indexOf(",") > -1){
var results = result.response.split(", ");
// show the results to the left of the form if there are any
$(tab + ' #results').removeClass('hide');
for (i=0; i < results.length; i++){
$(tab + " #list").append('<li>' + results[i] + '</li>');
}
}else{
results = result;
$(tab + " #list").append('<li>' + results.response + '</li>');
}
}
});
return false;
});
这似乎不起作用,因为它仅适用于选项卡 1。任何其他选项卡都会对相应的 URL 进行操作,而不是调用该函数。
我希望能够对表单使用相同的功能,但我不确定如何在更改选项卡时针对特定表单。
感谢任何帮助! :)
【问题讨论】:
标签: javascript jquery ajax json forms