我有一个这样的按钮:
<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2'">BUTTON 1</button>
<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2'">BUTTON 2</button>如何使用javascript代码将&VAR3=3添加到onclick中:
<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2&VAR3=3'">BUTTON 1</button>
<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2&VAR3=3'">BUTTON 2</button>发布于 2019-10-27 21:16:04
假设用户当前浏览的网址是"page_test.php?VAR=1&VAR2=2",那么这段代码将把&VAR3=3附加到网址后面:
HTML:
<button class="buttons" onclick="insertParam('VAR3', '3')">BUTTON 1</button>JS:
function insertParam(key, value)
{
key = encodeURI(key);
value = encodeURI(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length;
var x;
while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0)
{
kvp[kvp.length] = [key,value].join('=');
}
document.location.search = kvp.join('&');
}发布于 2019-10-28 04:57:25
HTML:
像Max Voisard一样,假设用户当前浏览的网址是"page_test.php?VAR=1&VAR2=2",我会试着做得简单一点。
<button class="buttons" onclick="insertParam('VAR3', '3')">BUTTON 1</button>JS:
function insertParam(key, value)
{
key = encodeURI(key);
value = encodeURI(value);
return window.location.href + `&${ key }=${ value }`
}https://stackoverflow.com/questions/58579675
复制相似问题