优雅地修改现有链接's参数
Elegantly modifying an existing link's parameters with javascript
我想用javascript找到这个链接中有很多参数的部分:
<a class="" data-method="post" href="/daily_drills?commonality%5B%5D=category&commonality%5B%5D=2&daily_drill%5Bgroup_id%5D=2&drill_ids%5B%5D=7&drill_ids%5B%5D=4&drill_ids%5B%5D=3&group=2" id="done-button" rel="nofollow">Done</a>
并在参数drill_ids 中添加/删除数字
在上面的示例中,drill_ids
参数包含["7", "4", "3"]
:
drill_ids%5B%5D=7&drill_ids%5B%5D=4&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)
相关文章:
- 如何使用JQuery在HTML中创建包含字符串参数的引号的onclickjavascript链接
- Facebook共享动态参数链接
- 如何在 html 链接中发送参数以及如何检索它
- 通过javascript将url参数传递到多个不同的href链接中
- “add”函数适用于不同的链接/参数组合
- 如何创建一个链接,该链接使用相应的参数打开到其他链接
- 将多个Url参数传递给链接
- 在coffeescript中链接jquery方法和参数
- 使用JavaScript向链接添加参数
- ES6承诺:如何用参数链接函数
- 优雅地修改现有链接's参数
- 如何在使用模式框的混合Form/HEF链接中添加其他GET参数
- 在javascript中创建一个链接来设置公共渲染参数的值
- 带有文本参数的Facebook共享者链接
- JS:将单参数函数转换为可链接函数
- 将参数传递给带有锚点的链接
- 更改基于目标将 URL 参数追加到链接的方式
- 带有传递参数的角度承诺链接
- 将承诺与多个参数链接在一起
- html<a>将javascript函数与参数链接