优雅地修改现有链接';使用javascript创建参数

优雅地修改现有链接';使用javascript创建参数,javascript,jquery,ruby-on-rails,regex,params,Javascript,Jquery,Ruby On Rails,Regex,Params,我想使用javascript查找此链接中包含大量参数的部分: <a class="" data-method="post" href="/daily_drills?commonality%5B%5D=category&amp;commonality%5B%5D=2&amp;daily_drill%5Bgroup_id%5D=2&amp;drill_ids%5B%5D=7&amp;drill_ids%5B%5D=4&amp;drill_ids%5B%5

我想使用javascript查找此链接中包含大量参数的部分:

<a class="" data-method="post" href="/daily_drills?commonality%5B%5D=category&amp;commonality%5B%5D=2&amp;daily_drill%5Bgroup_id%5D=2&amp;drill_ids%5B%5D=7&amp;drill_ids%5B%5D=4&amp;drill_ids%5B%5D=3&amp;group=2" id="done-button" rel="nofollow">Done</a>
我有一个方法,当用户单击页面上的数字时触发,如果他们单击“7”,我想从drill_id参数中删除“7”。如果他们单击参数中不存在的数字,我想将其附加到drill_id参数中

  • 因为我可以将此链接渲染为部分链接,所以我考虑使用附加的drill_ids参数重新渲染整个链接,但在较弱的连接上不会有即时响应时间

  • 我可以用regex风格添加/删除drill_id%5B%5D=7&(对于数字7),但似乎有一种更干净的方法可以做到这一点


关于如何处理这个问题,有什么建议吗?

我最后做了一个简单的javascript匹配,因为我无法想出一个聪明的干净解决方案:

// I build up a string that I want to replace the old string with

// create a list of the ids that I wanted to append
listOfIds = ""
arrayOfIds.forEach (id) ->
  listOfIds = listOfIds+id

// grab the old link in it's entirety
oldLink = $("#done-button").attr("href")
console.log(oldLink)

// grab the string from the old link I don't want
match = oldLink.match(/(?:group_id%5D=2)(.*)(?=&group=)/)[1]

// replace the old string with the new string
newLink = oldLink.replace(match, listOfIds)

// changed the href attribute on the link
$("#done-button").attr('href', newLink)

与其读取/解析链接,不如每次从头开始重新构建它。这样做所花费的cpu/代码时间比构建一个小型解析器来拆分链接要少。您必须解析每个,您可以使用拆分函数来获取每个单独的钻取ID并检查其中的值,但我可能会按照Marc B的建议将参数存储在锚元素数据对象的对象中,然后,每当更改其中一个属性时,使用$.param重新生成param字符串。
// I build up a string that I want to replace the old string with

// create a list of the ids that I wanted to append
listOfIds = ""
arrayOfIds.forEach (id) ->
  listOfIds = listOfIds+id

// grab the old link in it's entirety
oldLink = $("#done-button").attr("href")
console.log(oldLink)

// grab the string from the old link I don't want
match = oldLink.match(/(?:group_id%5D=2)(.*)(?=&group=)/)[1]

// replace the old string with the new string
newLink = oldLink.replace(match, listOfIds)

// changed the href attribute on the link
$("#done-button").attr('href', newLink)