我有 3 个针对卖家、技能和城市的选择框
对于卖家
<select data-placeholder="Select Seller..." class="sellereselect">
<option>test1</option>
<option>test2</option>
<option>test3</option>
<option>test4</option>
</select>
对于技能
<select data-placeholder="Select skills..." class="sellereselect">
<option>test1</option>
<option>test2</option>
<option>test3</option>
<option>test4</option>
</select>
针对城市
<select data-placeholder="Select city..." class="sellereselect">
<option>test1</option>
<option>test2</option>
<option>test3</option>
<option>test4</option>
</select>
我想如果有人选择卖家而不是网址重定向到
www.test.com/?seller=test1
如果有人选择卖家和城市,则 url 重定向到
www.test.com/?seller=test1&skills=test1
如果参数已在 url 中,则会更新参数中的值。
我已经尝试了大多数方法,例如窗口替换、更改选择框的事件,但没有任何帮助我!请任何人帮助我!!
最佳答案
我会在每个选择上设置一个数据属性,例如data-param="city"
,然后像下面一样循环它们。
注意js中的encodeURIComponent(),如果没有它,值包含“&”、“?”、“/”、“=”等字符的选项会破坏代码,就像第二个选择框中的选项 4 一样。
$('.sellereselect').change(function(){
var params =[];
$('.sellereselect').each(function(){
$this=$(this);
if(!$this.val()=='') params.push($this.data('param')+'='+encodeURIComponent( $this.val() ));
});
$('#urlDislay').text('www.test.com/?'+params.join('&')); // for display
// windox.location = 'www.test.com/?'+params.join('&'); // for you actual use
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
For seller
<select data-placeholder="Select Seller..." class="sellereselect" data-param="seller">
<option></option>
<option>test1</option>
<option>test2</option>
<option>test3</option>
<option>test4</option>
</select>
<br>
For skills
<select data-placeholder="Select skills..." class="sellereselect" data-param="skills">
<option></option>
<option>test1</option>
<option>test2</option>
<option>test3</option>
<option>test&4</option> <!-- note the encodeURIComponent() in the js, without it this option would break the code -->
</select>
<br>
For city
<select data-placeholder="Select city..." class="sellereselect" data-param="city">
<option></option>
<option>test1</option>
<option>test2</option>
<option>test3</option>
<option>test4</option>
</select>
<br>
<br>
<div id="urlDislay">www.test.com/?</div>
关于javascript - 根据选择选项使用 jquery 更新或替换 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32840406/