我希望有一个带有多个下拉过滤器的博客样式页面。当用户更改时,我想做一个onChange事件,向URL添加一个参数,然后调整内容。我很想用AJAX来完成这个任务,但是我想先让这个功能发挥作用。
以下是基本形式:
<form action="" method="GET">
<select name="channel">
<option value="" selected>Choose Channel</option>
<option value="facebook-ads">Facebook ads</option>
<option value="instagram-ads">Instagram ads</option>
</select>
<select name="brand">
<option value="" selected>Choose Brand</option>
<option value="brand-1">brand 1</option>
</select>
</form>当它是一个选择时,我只是使用内联的onchange事件。
我正在寻找这个url来更改为这样的一个例子:
exampleurl.com/blog/?channel=facebook-ads&brand=brand-1
我希望能够有一个脚本,允许在选择值时将其中一个或两者添加到URL中。我不想使用提交按钮。
因此,如果URL中已经有一个参数,并且用户从另一个下拉列表中选择一个值,那么该参数将被添加到URL中,不会删除其他值。
真希望有人能帮我做这件事,因为经过一天的搜寻和尝试,我仍然没有进一步。
发布于 2021-06-27 12:59:51
满足您的需求的简单解决方案:
<form action="" method="GET" id="myForm">
<select name="channel" id="0" onChange="changeURL(0)">
<option value="" selected disabled>Choose Channel</option>
<option value="facebook-ads">Facebook ads</option>
<option value="instagram-ads">Instagram ads</option>
</select>
<select name="brand" id="1" onChange="changeURL(1)">
<option value="" selected disabled>Choose Brand</option>
<option value="brand-1">brand 1</option>
<option value="brand-2">brand 2</option>
<option value="brand-3">brand 3</option>
</select>
</form>
<p id="test"></p>
<script>
var filters = [,]; // create an array with empty values (only 2 in this case)
function changeURL(a) {
var yourUrl = "https://yourdomain.com"; // your url
filters[a] = document.getElementById(a).value; // set the value of the selected filter inside the array
var preFilter = "?"; // blank url will need a "?" to start with your filters
for(var i=0; i<filters.length; i++) {
aName = document.getElementById(i).name; // get the name of the filter
yourUrl += preFilter + aName + "=" + filters[i];
preFilter = "&";
}
document.getElementById("test").innerHTML = yourUrl; // test output of the new url
}
</script>
https://stackoverflow.com/questions/68146424
复制相似问题