我有一个计数器
按钮,单击时会增加数字。
我还有一个类似 http://localhost:5000/x/
的 URL。
我想要的是:
在 URL 末尾打印 counter
值。
例如:
如果 counter=3,
我想去 http://localhost:5000/x/3
;
我的按钮类型是submit
,它增加了计数器的值并进入页面http://localhost:5000/x/counter
。但是,我收到 404 错误,因为数据位于 http://localhost:5000/x/3
上。这是代码。
<form action="http://localhost:5000/x/counter">
<script>
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
谢谢。另外,我不使用任何框架,我想仅使用 JavaScript 来处理它。
编辑:
感谢您的回答。我通过使用 window.location.href
函数解决了这个问题。
最佳答案
使用页面 URL 检索计数器
var counter = location.href.substring(location.href.lastIndexOf('/')+1);
counter = parseInt(counter);
counter += 1;
使用计数器设置 myform 操作
document.myform.action = location.href.substring(0,location.href.lastIndexOf('/'))+counter;
为您的表单命名
<form name='myform'>
关于javascript - 如何在 JavaScript 中的 URL 末尾添加变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44032798/