【发布时间】:2015-10-19 21:24:58
【问题描述】:
我想在单击导航栏上的链接时将内容异步加载到我的页面中。虽然,使用 .load() 方法有效,但我很难弄清楚如何使 promise 对象以相同的方式工作。我也很困惑为什么当我点击“主页”时我的表单是可见的,即使我将它设置为隐藏。
http://jsfiddle.net/Piq9117/Lzw514md/
// Navigation
var navigation = (function () {
var $nav = $('#navigation a');
var $page = $('#page');
var $container = $('#container');
$nav.on('click', function (e) {
e.preventDefault();
$page.remove();
dataservice.getPage()
.done(function (data) {
$container.html($(data).find('#page'));
})
.fail(function (jqXHR, statusText, err) {
alert(err);
})
})
// the .load works fine..
// $nav.on('click', function(e) {
// e.preventDefault();
// var url = $(this).attr('href');
// $page.remove();
// $container.load(url + ' #page');
// })
})();
// Promise object, passed to navigation
var dataservice = (function () {
var getPage = function () {
var url = $(this).attr('href'); // this returns undefined
return $.ajax({
type: 'GET',
url: url,
})
}
return {
getPage: getPage
}
})();
// chache/hide/show form
(function () {
var form = {
init: function () {
this.cacheDom();
this.events();
},
cacheDom: function () {
this.$container = $('.container');
this.$page = this.$container.find('#page');
this.$showbtn = this.$container.find('#showbtn');
this.$form = this.$page.find('#form');
this.$form.hide();
this.$submitbtn = this.$page.find('#submitbtn');
},
events: function () {
this.$showbtn.on('click', this.showForm.bind(this));
this.$submitbtn.on('click', this.hideForm.bind(this));
},
showForm: function () {
this.$form.fadeIn(300);
this.$showbtn.hide(300);
},
hideForm: function (e) {
e.preventDefault(300);
this.$form.hide(300);
this.$showbtn.show(300);
}
}
form.init();
})();
【问题讨论】:
-
首先,您从加载中返回的表单不像初始加载时那样具有
display:none样式。 -
@DataHerder 使用 .hide() 方法隐藏表单。
-
好吧,在您通过 ajax 加载数据后,它肯定不会被调用。
-
是的,因为我必须委托或绑定它。所以我切换到只显示它并用 jquery 更改显示。
标签: javascript jquery ajax asynchronous