Javascript 将select值传递给链接URL参数

Javascript 将select值传递给链接URL参数,javascript,html,string,function,Javascript,Html,String,Function,我有一个Buy按钮,用户可以点击该按钮购买特定产品。 这将把他们带到我创建的购买表单。 该表单上的一个字段使用URL参数,以便知道用户想要购买哪种产品 因此,我想做的是在页面上的某个地方(购买按钮所在的位置)有一个HTML选择字段,允许用户在那里选择产品。 然后,当他们点击Buy按钮时,它会通过URL传递所选的值。例如: // Some content here promoting the three products. // Now I want a select field for the

我有一个
Buy
按钮,用户可以点击该按钮购买特定产品。
这将把他们带到我创建的购买表单。
该表单上的一个字段使用URL参数,以便知道用户想要购买哪种产品

因此,我想做的是在页面上的某个地方(购买按钮所在的位置)有一个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>
//这里有一些推广这三种产品的内容。
//现在我需要一个选择字段,供用户从三种产品中选择一种,如下所示。
产品1
产品2
产品3
//然后我在这里有更多的内容,展示每种产品的优缺点。
//最后,我在页面底部有一个buy按钮,可以将他们带到带有购买表单的页面。
//在这里,我想获取select字段的值,并通过如下“product”参数传递它。

使用JavaScript执行此操作:

document.getElementsByClassName("button")[0].addEventListener("click", function(event) {
    var product = document.getElementById("productSelect").value;
    event.target.setAttribute("href", "/buy?product=" + product);
});

这将起作用。

感谢您的回复,但是您能否澄清我是如何准确使用此JavaScript的。我对JavaScript不是很熟悉,所以我不确定该把它放在哪里,或者如何使用它来链接我的按钮。另外,这个JavaScript会影响我所有的按钮吗?我注意到getElementsByClassName引用了“button”,页面上有几个引用。然而,我只希望这一个购买按钮受到影响。不是所有的。