我有一个购买
按钮,用户可以点击该按钮来购买特定产品。
这会将他们带到我构建的购买表单。
该表单上的一个字段使用 URL 参数,因此它知道用户想要购买哪种产品。
所以我想做的是在页面之前的某个位置(Buy
按钮所在的位置)添加一个 HTML 选择字段,并允许用户在那里选择产品。
然后,当他们单击 Buy
按钮时,它会通过 URL 传递所选值。例如:
// Some content here promoting the three products.
// Now I want a select field for the user to choose one of the three products, like this.
<select id="productSelect">
<option value="product1">Product 1</option>
<option value="product2">Product 2</option>
<option value="product3">Product 3</option>
</select>
// Then I have some more content here showing the pros/cons of each product.
// Finally, I have a buy button at the bottom of the page that takes them to the page with the purchase form.
// Here is where I want to grab the value of the select field and pass it through via the "product" parameter like this.
<a class="button" href="/buy/?product='select value here'">Buy</a>
最佳答案
使用 JavaScript 执行此操作:
document.getElementsByClassName("button")[0].addEventListener("click", function(event) {
var product = document.getElementById("productSelect").value;
event.target.setAttribute("href", "/buy?product=" + product);
});
这会起作用。
关于javascript - 将选择值传递给链接 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53147127/