在我的情况下,当您单击一个按钮时,它会在我的字符串上添加一个get参数,但如果再次单击它应该为该参数的值添加连字符。这实际上将用于下降和上升通过添加单个字符的javascript字符串操作
我当前的代码是:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="script.js"></script>
</head>
<body>
<p id ='demo'></p>
<button column-data='age'>Age</button>
<button column-data='height'>Height</button>
<button column-data='weight'>Weight</button>
</body>
<script>
document.getElementById("demo").innerHTML = window.location.href;
$(function() {
$('button').click(function(){
data = $(this).attr('column-data');
order_regex_asc = new RegExp('[&?]order=' + data, 'g')
order_regex_desc = new RegExp('[&?]order=-' + data, 'g')
_loc = window.location.href
if(data){
if (_loc.search(/[?]order/) == -1){ // Conditional to start GET parameter
_loc = _loc + '?order=' + data;
window.location = _loc
}else{
if (_loc.search(order_regex_asc) != -1){ // Conditional to make this decending
console.log('dean');
// _loc = _loc.replace(order_regex_asc, '')
// data = '-'+data
}else if (_loc.search(order_regex_desc) != -1){ // Conditional to make this ascending
console.log('armada');
// _loc = _loc.replace(order_regex_desc, '')
}else{
window.location = _loc + '&order=' + data;
}
}
document.getElementById("demo").innerHTML = _loc;
}
});
});
</script>
</html>
这里是我的plunker:https://plnkr.co/edit/nE6MK7PWb54GkXOdIojn?p=preview
举例来说,在我的plunker,如果你点击“年龄”按钮将添加?订单=年龄。如果第二次点击它,adde应该是?order = -age。如果你第三次点击它,那么它应该回到?order = age。如果你继续点击,那么它会在添加删除连字符时来回切换。
我已经在这里停留几个小时,它已经这么长时间,因为我在javascript
也许你可以有一个对象并保存您的选项,并设置一个标志,知道是否启用或禁用它。 – claudios
@claudios,你能提供一个代码来展示你的想法吗? –
我知道这不是代码审查,但你可以考虑使用[window.pushState()](https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries)和[窗口。 replaceState()](https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_replaceState()_method),除非你真的需要页面重新加载... –