我想在复选框单击时重写url参数值,类似于LinkedIn Advance搜索。



<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
  <script type='text/javascript'>

  $(document).ready(function () {
$('input[type=checkbox]').click(function (e) {
var seasoning = jQuery.map($(':checkbox[id=seasoning\\[\\]]:checked'), function (n, i) {return n.value;}).join(',');

window.location ='example.com?seasoning='+seasoning;

});

});
</script>

<h3>Filter recepies:</h3>

<div>
<p>Select vegetables</p>
<label><input type="checkbox" id="vegetables[]" value="potato"> Potato</label><br>
<label><input type="checkbox" id="vegetables[]" value="onion"> Onion</label><br>
<label><input type="checkbox" id="vegetables[]" value="tomato"> Tomato</label><br>
</div>

<div>
<p>Select seasoning</p>
<label><input type="checkbox" id="seasoning[]" value="salt"> Salt</label><br>
<label><input type="checkbox" id="seasoning[]" value="pepper"> Pepper</label><br>
<label><input type="checkbox" id="seasoning[]" value="chilli"> Chilli Flakes</label><br>
</div>





我想要的结果

Click1:当我从蔬菜中单击“土豆”时,我的网址应类似于
example.com?vegitables=土豆

Click2:当我从蔬菜中单击洋葱时,我的网址应为
example.com?vegitables=土豆,洋葱

Click3:当我从调味料中单击盐时,我的网址应为
example.com?vegitables=土豆,洋葱和调味料=盐

Click4:当我从调味料中单击胡椒粉时,我的网址应为
example.com?vegitables=土豆,洋葱和调味料=盐,胡椒粉

最佳答案

这是你可以做的



$(document).ready(function () {
  $('input[type=checkbox]').click(function (e) {
  var seasoning = '', tempArray = [];
  $('input[name="vegetables[]"]:checked').each(function(){
      tempArray.push($(this).val());
  })
  if(tempArray.length !== 0){
     seasoning+='vegetables='+tempArray.toString();
     tempArray = [];
  }

  $('input[name="seasoning[]"]:checked').each(function(){
      tempArray.push($(this).val());
  })
  if(tempArray.length !== 0){
     seasoning+='&seasoning='+tempArray.toString();
  }

 // window.location ='example.com?seasoning='+seasoning;
 console.log('example.com?'+seasoning);

  });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>Select vegetables</p>
<label><input type="checkbox" name="vegetables[]" value="potato"> Potato</label><br>
<label><input type="checkbox" name="vegetables[]" value="onion"> Onion</label><br>
<label><input type="checkbox" name="vegetables[]" value="tomato"> Tomato</label><br>
</div>

<div>
<p>Select seasoning</p>
<label><input type="checkbox" name="seasoning[]" value="salt"> Salt</label><br>
<label><input type="checkbox" name="seasoning[]" value="pepper"> Pepper</label><br>
<label><input type="checkbox" name="seasoning[]" value="chilli"> Chilli Flakes</label><br>
</div>





为了简单起见并进行进一步的编辑,这里是工作JSFIDDLE的链接

09-28 09:12