我在 Internet 和 stackoverflow 上搜索了如何触发二次点击功能,这就是我的发现:
$('.elementclass').toggle(
function(){
//on odd
},
function(){
//on even
});
这是完美的。现在根据这个,我尝试更改我的文档的 URL,但有些东西不起作用。这是我的代码:
$('.orderby').toggle(
function(){
document.location.href+='?orderby='+$(this).val()+'ASC';
},
function(){
document.location.href+='?orderby='+$(this).val()+'DESC';
});
其中 $(this).val()
将类似于名称或日期...
我想要完成的是:第一次点击按钮时,URL 变为 http://blablabla/page.php?orderby=nameASC然后在第二次点击时,URL 变为 http://blablabla/page.php?orderby=nameDESC .
那么我的代码有什么问题吗?
我不想在用户单击按钮时刷新页面,我只想添加一些(在本例中为一个)参数,这些参数稍后可以使用 $_GET 但在同一页面上。document.URL 可以需要在第一次点击和第二次点击时更新 +=?orderby=nameASC +=?orderby=nameASC 并且 document.URL 更新 +=?orderby=nameDESC。
最佳答案
您的页面发生变化,因此脚本会再次加载。 你需要测试你有什么 url
已更新以处理不同的 orderby 值
$(document).ready(function() {
$('.orderby').click(
function(){
var srch = location.search;
if (srch) srch = srch.substring(1); // lose the ?
var val = $(this).val();
if (srch.indexOf(val+"ASC")!=-1)
srch = srch.replace(val+"ASC",val+"DESC");
else if (srch.indexOf(val+"DESC")!=-1)
srch = srch.replace(val+"DESC",val+"ASC");
else if (!srch || srch.indexOf("orderby")!=-1) {
// if srch was empty or contained another value than this'
srch ='orderby='+$(this).val()+'ASC';
}
var loc = (location.search)?location.href.split("?")[0]:location.href;
window.location = loc + "?"+srch;
});
});
PS:document.location.href 在很多年前就被弃用了。请改用 document.URL 或 window.location.href
PPS:正如 MilkyWayJoe 正确指出的那样 - 何必呢 - 如果页面从服务器加载到当前页面而不是 iframe 或 ajaxed,然后在服务器上设置按钮的值并有一个正常的链接 - 那即使关闭 JS 也会使其工作
更新 2
如果你使用 AJAX,你想做类似的事情
$(document).ready(function() {
if (location.hash.indexOf(....) {
// find the element which is mentioned in the orderby and click it
var $elem = ....
$elem.click(); // or trigger
}
$('.orderby').toggle(
function(){
$("#someLabel").html("DESC");
var orderBy = $(this).val()+'ASC';
location.hash = orderBy; // now URL will be ...#nameASC
$("#content").load('soneserverprocess?orderby='+orderBy);
},
function(){
$("#someLabel").html("ASC");
var orderBy = $(this).val()+'DESC';
location.hash = orderBy; // now URL will be ...#nameDESC
$("#content").load('someserverprocess?orderby='+orderBy);
});
});
如果你想使用浏览器内排序,使用其中之一
http://www.tripwiremagazine.com/2012/02/jquery-filter-sort-plugins.html
有
$(document).ready(function() {
if (location.hash.indexOf(....) {
// find the element which is mentioned in the orderby and click it
var $elem = ....
$elem.click(); // or trigger
}
$('.orderby').toggle(
function(){
$("#someLabel").html("DESC");
var orderBy = $(this).val()+'ASC';
location.hash = orderBy; // now URL will be ...#nameASC
$("#content").sort(....); // depending on plugin
},
function(){
$("#someLabel").html("ASC");
var orderBy = $(this).val()+'DESC';
location.hash = orderBy; // now URL will be ...#nameDESC
$("#content").sort(....); // depending on plugin
});
});
关于javascript - 在第一次和第二次点击时更改 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10095714/