单击a.format24
时,我希望页面重新加载然后.fadeOut()
一个元素并更改一些文本。显然,下面的代码设置方式是错误的,因为页面重新加载和 jQuery 功能是同时发生的。通过 location.reload()
运行 jQuery 函数不起作用,所以我没有想法。
$(document).ready(function() {
$("a.format24").toggleClick(function() {
location.reload();
$("div.toggleWrap").fadeOut();
$(this).text("Use am/pm format");
}, function() {
location.reload();
$("div.toggleWrap").fadeIn();
$(this).text("Use 24-hour format");
});
});
最佳答案
解决此问题(如果您实际上必须重新加载页面)的通常方法是向 URL 添加一个参数,然后加载该 URL。因此,如果您的原始 URL 是 http://example.com/play.html
,那么您将加载 URL:http://example.com/play.html?special= 1
。
您在页面上的启动代码将检查 URL 的查询参数中的 special=1
,如果找到,它将在页面加载时启动特殊行为。
显然,您必须提前计划要支持的特殊页面加载行为,但这是非常可行的。
好的,假设当您第二次加载页面时,您希望更改 a.format24 文本。我们将对其进行设计,使 URL 中的 time=24
表示 24 小时格式,而 URL 中的 time=12
表示 12 小时上午/下午格式。如果两者都不存在,则默认为 12 小时格式。
在处理URL中的搜索参数时,有3种情况需要处理:
- 没有搜索参数
- 有一些搜索参数,但不是您要找的参数
- 有一些搜索参数,包括您要查找的参数
根据您找到的条件,您必须以不同方式处理使用所需搜索参数构建新 URL。这就是为什么下面的代码具有三个不同的分支来构建 URL。
// initialize the time format based on what's in the search parms of the URL
$(document).ready(function() {
var format24 = /time=24/.test(document.location.search);
if (format24) {
$("a.format24").data("format", 24).hide().text("Use 24-hour format").fadeIn();
}
});
$(document).ready(function() {
// upon click, switch to the other time format in the URL
$("a.format24").click(function() {
var self = $(this), newFormat;
// if currently in 24 hour mode
if (self.data("format") == 24) {
newFormat = "time=12";
} else {
newFormat = "time=24";
}
var newUrl = location.href;
// if no search value yet in the URL
if (!window.location.search) {
// no parms on the URL at all so
// just add ?time=24 to the end of the URL
newUrl += "?" + newFormat;
} else if (window.location.search.indexOf("time=") !== -1) {
// replace any existing format with the new one
newUrl = newUrl.replace(/time=\d+/, newFormat);
} else {
// some search params exist, but not the time format
// so add onto the end after the other search params
newUrl += "&" + newFormat;
}
self.fadeOut(500, function() {
window.location = newUrl;
});
});
});
工作演示:http://jsfiddle.net/jfriend00/2h3KE/
另一种方法是根本不重新加载页面,只使用 DOM 操作根据需要更改页面而无需重新加载。
关于javascript - 如何在javascript中刷新当前页面然后调用jQuery函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22675806/