我有一个脚本,可以添加点击元素的值.但是 - 我想在点击时将值替换为新值.
例:
<ul class="acfilter">
<li><a href="reset">reset</a></li>
<li><a href="One">One</a></li>
<li><a href="Two">Two</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
脚本
$(document).ready(function() {
$('ul.acfilter li a').on('click', function(e) {
e.preventDefault();
if ($(this).attr('href') != "reset") {
if (location.href.indexOf('?') === -1) {
location.href = location.href + "?fss=" + $(this).attr('href');
} else {
location.href = location.href + "+" + $(this).attr('href');
}
} else {
location.href = location.origin + location.pathname;
}
});
});
Run Code Online (Sandbox Code Playgroud)
第一个参数onclick给出?fss=one
了第二个点击你得到的?fss=one+two
.重置链接清除它.
但是 - 我想用点击上的"两个"值替换"一"值.该值是动态的 - 所以我不能只使用已知值执行If/Else url.replace.
我该怎么做呢?
编辑:
忘记提及url中可以有其他参数.例:
首先点击给出
?fss=one
Run Code Online (Sandbox Code Playgroud)
并且当做一个给出我提到的其他参数的动作时,它给出了:
?param=list&fss=one
Run Code Online (Sandbox Code Playgroud)
这是正确的使用用户brijesh chowdary lavu的脚本.param = list是一个始终必须是第一个的参数,并且编写为执行此操作并从列表更改为largelist,这也适用于该脚本.
问题是当我第二次点击我的特定课程时 - 而不是来自
?param=list&fss=one
Run Code Online (Sandbox Code Playgroud)
至
?param=list&fss=two
Run Code Online (Sandbox Code Playgroud)
它取代了一切
?fss=one
Run Code Online (Sandbox Code Playgroud)
尝试这个。
$('ul.acfilter li a').on('click', function(e) {
e.preventDefault();
if ($(this).attr('href') != "reset") {
if (location.href.indexOf('?') === -1) {
location.href = location.href + "?fss=" + $(this).attr('href');
} else {
location.href = location.origin + location.pathname + "?fss=" + $(this).attr('href');
}
} else {
location.href = location.origin + location.pathname;
}
});
Run Code Online (Sandbox Code Playgroud)
或者使用简单的字符串方法,您可以向脚本中添加一个函数,如下所示,这样其他参数就不必更改:
$(document).ready(function() {
$('ul.acfilter li a').on('click', function(e) {
e.preventDefault();
if ($(this).attr('href') != "reset") {
if (location.href.indexOf('?') === -1) {
location.href = location.href + "?fss=" + $(this).attr('href');
} else {
location.href = changeParameter(window.location.toString(),"fss",$(this).attr('href'));
}
} else {
location.href = location.origin + location.pathname;
}
});
});
function changeParameter(str,par,val)
{
var t1 = str.indexOf(par);
var t3 = t1+par.length+1;
var t2= str.indexOf("&",t3);
if(t2==-1)
{
return str.substring(0,t3)+val;
}
else
{
return str.substring(0,t3)+val+str.substring(t2);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
167 次 |
最近记录: |