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

标签 javascript html

我有一个计数器按钮,单击时会增加数字。
我还有一个类似 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/

相关文章:

html - 在响应式网页设计中重叠时裁剪图像

javascript - 使用jsplumb动态拖动和连接angular6中创建的节点

javascript - 表单字段文本区域计数

javascript - Angular-nvD3 条形图 y 轴缩放错误(AngularJS)

javascript - 如何在R Shiny数据表中设置列宽?

php - 只允许使用htaccess访问一个php文件

html - CSS父/兄弟选择器

javascript - 使用jQuery点击元素触发css :active

javascript - 从嵌套对象中并行数组的属性获取总计

javascript - 类型错误 : 'undefined' is not a function with Tablesorter only in Safari