javascript - 将选择值传递给链接 URL 参数

标签 javascript html string function

我有一个购买按钮,用户可以点击该按钮来购买特定产品。
这会将他们带到我构建的购买表单。
该表单上的一个字段使用 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/

相关文章:

javascript - 如何用B替换元素A并在变量中包含B对象?

javascript - 更改 NativeScript TabView 默认行为

c++ - 将 from_string 与提升日期一起使用

java - 从集合中移除元素

提取文件路径多段的Python函数

javascript - 使用 Dojo AMD 加载器加载 jQuery 问题

javascript - 如何计算大小与当前索引相关的数组的运行时复杂度?

javascript - onclick ="alert(' 你好 !');window.close();"

java - 解析复杂的 li 标签

html - 避免继承父级的css效果