我正在尝试动态替换url值,我正在使用replace,因为我不希望每次点击都重复该值
我当然不是世界上最好的编码器,我不确定我的语法是否有效。
我试图在下面完成的一般想法是页面上有几个网址,在任何给定时间只显示一个我使用滑块以无缝方式隐藏/显示每个网址。
我想将一个位置传递给javascript函数(它将是一个数字),该函数应该获取位置编号并替换页面上所有href =“”中的部分。
但我似乎无法让它发挥作用。
function getlocation(loc) {
$('a').each(function() {
var location = $(this).attr('href');
$(this).attr('href').replace("&location=100", "&location=loc");
console.log('error');
});
}
<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>
<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>
<feildset>
<input id="mtl" name="location" type="radio" checked>
<label for="mtl" onclick="getlocation(mtl)">Montreal</label>
<br>
<br>
<input id="frkfrt" name="location" type="radio" onclick="">
<label for="frkfrt" onclick="getlocation(frkfrt)">Frankfurt</label>
</feildset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
eval
一样糟糕 - 使用Javascript正确地附加处理程序,以使这些问题不太可能发生。replace
不会改变原始字符串 - 字符串是不可变的。相反,您需要明确分配给href
s以便更改它们。getlocation
中,你必须将loc
变量与&location=
连接起来['mtl', 'frkfrt'].forEach(loc => {
document.querySelector(`[for="${loc}"]`).onclick = () => getlocation(loc);
});
function getlocation(loc) {
document.querySelectorAll('a').forEach(a => {
a.href = a.href.replace(/&location=.*$/, "&location=" + loc);
});
}
<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>
<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>
<feildset>
<input id="mtl" name="location" type="radio" checked>
<label for="mtl">Montreal</label>
<br>
<br>
<input id="frkfrt" name="location" type="radio">
<label for="frkfrt">Frankfurt</label>
</feildset>
如果我很清楚你需要什么,请尝试替换
$(this).attr('href').replace("&location=100", "&location=loc");
同
$(this).attr('href').replace("&location=100", "&location=" + loc);