为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Ajax 中复选框中的多个值管理 url 参数

使用 Ajax 中复选框中的多个值管理 url 参数

PHP
芜湖不芜 2023-11-03 20:43:00
我能够根据复选框选择向 URL 添加/删除参数。现在,如果选中多个复选框,我希望特定 URL 参数具有多个值。我改编了之前的答案片段以反映我陷入困境的地方。选择多个复选框时,会添加参数和值,而我只需要添加值。我怎样才能得到http://example.com/?param=foo,bar而不是http://example.com/?param=foo&param=bar当我检查foo和bar?const url = 'http://example.com' // demo version// const url = location.href - live versionconst urlObj = new URL(url);const params = urlObj.searchParamsconst $checks = $(':checkbox')// on page load check the ones that exist un urlparams.forEach((val, key) => $checks.filter('[name="' + key + '"]').prop('checked', true));        $checks.change(function(){    // append when checkbox gets checked and delete when unchecked    if(this.checked){                //here I check if there is already the parameter in url    if (url.indexOf(this.value) > -1) {        //and try to append only this name with a comma as separator from previous one        params.append(',',this.name )    } else {      params.append(this.value,this.name )    }    }else{        params.delete(this.name);           }    // do your page load with location.href = urlObj.href     console.clear()     console.log(urlObj.href);})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><label>Foo <input type="checkbox" name="foo" value="param"/></label> <label>Bar <input type="checkbox" name="bar" value="param"/></label><label>Zzz <input type="checkbox" name="zzz" value="param"/></label>
查看完整描述

目前暂无任何回答

  • 0 回答
  • 0 关注
  • 60 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信