I would like to change the parameters in the query string. I wish to have this effect: If I click the first time, the query-string changes, and if I click the second time, the query string changes again. I would to like have this effect for all elements and must be independent of each other. In the my code below, I don't have what I would like. because If I click the first element, its query-string changes, but now If i click the second element nothing happening, I have to click it two times to change its query string. Don't worry for the refresh page after click, because it will be ajax call. I just need to understand how to change the parameters correctly. I apologize if the request is not clear. Thanks for your help.
<a href="quantity-0" onclick="updateParams(this)">CHANGE PARAMETERS<a/><br><br>
<a href="quantity-0" onclick="updateParams(this)">CHANGE PARAMETERS<a/><br><br>
<a href="quantity-0" onclick="updateParams(this)">CHANGE PARAMETERS<a/><br><br>
<script>
var clicked = true;
function updateParams(abba){
if(clicked){
var a = abba.href.replace('quantity-0', 'add-0');
abba.setAttribute('href', a);
}else{
var a = abba.href.replace('add-0','quantity-0');
abba.setAttribute('href',a);
}
clicked = !clicked;
}
</script>
Try this -
<script>
function updateParams(abba){
if(abba.href.search('quantity-0') > -1) {
var a = abba.href.replace('quantity-0', 'add-0');
abba.setAttribute('href', a);
}
else {
var a = abba.href.replace('add-0','quantity-0');
abba.setAttribute('href',a);
}
}
</script>
Hope this helps. Thanks!
You can fix this using closures:
<a href="quantity-0" onclick="makeUpdater(this)">CHANGE PARAMETERS<a/><br><br>
<a href="quantity-0" onclick="makeUpdater(this)">CHANGE PARAMETERS<a/><br><br>
<a href="quantity-0" onclick="makeUpdater(this)">CHANGE PARAMETERS<a/><br><br>
<script>
fucntion makeUpdater(abba) {
var clicked = true;
return function updateParams(){
if(clicked){
var a = abba.href.replace('quantity-0', 'add-0');
abba.setAttribute('href', a);
}else{
var a = abba.href.replace('add-0','quantity-0');
abba.setAttribute('href',a);
}
clicked = !clicked;
};
}
</script>
the problem was that you've had one variable for all buttons. You need separated for each one of them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.