优雅地修改现有链接's参数

Elegantly modifying an existing link's parameters with javascript

本文关键字:参数 链接 修改      更新时间:2024-03-31

我想用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>

并在参数drill_ids 中添加/删除数字

在上面的示例中,drill_ids参数包含["7", "4", "3"]:

drill_ids%5B%5D=7&amp;drill_ids%5B%5D=4&amp;drill_ids%5B%5D=3

我有一个方法,当用户单击页面上的数字时会触发,如果他们单击"7",我想从drill_ids参数中删除"7"。如果他们单击了params中不存在的数字,我想将其附加到drill_ids params中。

  • 由于我可以将此链接呈现为部分链接,所以我想用附加的drill_ids参数重新呈现整个链接,但在较弱的连接上不会有即时响应时间。

  • 我可以用正则表达式样式添加/删除drill_ids%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)