Javascript 随时更新HTML中的JS变量

Javascript 随时更新HTML中的JS变量,javascript,html,Javascript,Html,数字输入旁边有减号、加号按钮。下面是一个buy now按钮,用于从HTML获取值并传递到href URL每次单击减号/加号按钮(数量值更改)时,如何更新href URL中的数量? 我写了下面的代码,当单击减号/加号时,它只显示“新建”选项卡中的按钮。我需要更新同一页面中的按钮URL URL:product.php?id=1&addtocart=1&qty=1 <td id="pid">1</td> <but

数字输入旁边有减号、加号按钮。下面是一个buy now按钮,用于从HTML获取值并传递到href URL每次单击减号/加号按钮(数量值更改)时,如何更新href URL中的数量? 我写了下面的代码,当单击减号/加号时,它只显示“新建”选项卡中的按钮。我需要更新同一页面中的按钮URL

URL:
product.php?id=1&addtocart=1&qty=1

<td id="pid">1</td>
                    <button onclick="this.parentNode.querySelector('input[type=number]').stepDown();ifquantitychanges();"</button>
                    <input id="quantity" min="0" value="1" type="number" max="5">
                    <button onclick="this.parentNode.querySelector('input[type=number]').stepUp();ifquantitychanges();"></button>

        <script>
        
        function ifquantitychanges() {
        var qty= document.getElementById('quantity').value;
                    var pid= document.getElementById('pid').innerHTML;
        var loc = "product.php?id="+ pid + "&addtocart="+ pid + "&qty="+ qty;
        
        document.write('<a href="' + loc + '"><button>Add to cart</button></a>');
}
ifquantitychanges();
            </script>
1

您可以通过访问
window.location.href
变量来更改浏览器URL:)


您应该调用在输入中更改url的方法,在输入中更改您的值

我需要更改同一页面中按钮的href,而不是页面url。当我们读到“每次单击减号/加号按钮(数量值更改)时,如何更新url中的数量?”时,这一点并不清楚,它在“新建”选项卡中显示按钮,而不是在同一页面中更新。这应该由事件侦听器来解决。事实上,您不应该这样做。您的按钮onclick submit操作默认情况下应获取
中的数量并提交表单。不要动态更改按钮的URL。
var loc = "product.php?id="+ pid + "&addtocart="+ pid + "&qty="+ qty;
window.location.href = loc;