javascript - 根据选择选项使用 jquery 更新或替换 URL 参数

标签 javascript php jquery html

我有 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/

相关文章:

jQuery BlockUI : Is it possible to run a function after a user hits the "enter" key?

php - 表单提交后,滚动到表单

javascript - 从默认导入开 Jest 模拟异步函数

javascript - 为什么 saga 函数第二次不接受请求?

php - 将所有图像加入到其相关页面

php - 下拉列表在 Firefox 上消失

php - 这是什么格式[类似于 json]?

javascript - 将字符串化/encodeURIComponent 数据导出到文件时扩展崩溃

php - 应用程序访问服务器负载

javascript - 如果 id 不存在,为什么 $ ('#id' ) 返回 true?