简体   繁体   English

如何在JavaScript的URL末尾添加变量值?

[英]How to add value of variable at the end of URL in JavaScript?

I have a counter button which increases the number when clicked. 我有一个counter按钮,可以在点击时增加数量。
Also I have an URL like http://localhost:5000/x/ . 我也有一个像http://localhost:5000/x/的URL。

What I want is: 我想要的是:
Printing the counter value at the end of the URL. 打印URL末尾的counter值。

For example: 例如:
If counter=3, 如果counter = 3,
I want to go http://localhost:5000/x/3 ; 我想去http://localhost:5000/x/3 ;

My button type is submit and it increases the value of counter and goes the page http://localhost:5000/x/counter . 我的按钮类型是submit ,它增加了计数器的值,并进入页面http://localhost:5000/x/counter However, I got 404 Error because the data is on the http://localhost:5000/x/3 . 但是,我得到404错误,因为数据在http://localhost:5000/x/3 Here is the code. 这是代码。

<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>

Thanks.Additional I don't use any framework and I want to handle it just by using JavaScript. 谢谢。另外我不使用任何框架,我想通过使用JavaScript来处理它。

EDIT: Thanks for your answers. 编辑:谢谢你的回答。 I solved it by using window.location.href function. 我通过使用window.location.href函数解决了它。

Retrieve counter using url of page 使用页面的URL检索计数器

var counter = location.href.substring(location.href.lastIndexOf('/')+1);
counter = parseInt(counter);
counter += 1;

Set myform action using counter 使用计数器设置myform操作

document.myform.action = location.href.substring(0,location.href.lastIndexOf('/'))+counter;

Name your form 为表单命名

<form name='myform'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM