点击标签a时如何向href url添加参数?

时间:2018-06-14 09:59:05

标签: javascript

我想从home页面发送参数idcarts页面:

这是当前的代码,但它没有问题:

<a  href="carts" onclick="addParam();">detail</a>
<script>

     function addParam()
     {
         var url = window.location.href;
         var listId = localStorage.getItem('IDs', '');          
         url=url+ "?id=" +listId;
         window.location.href = url;
     }
</script>

单击标记a?

时如何向href url添加参数

1 个答案:

答案 0 :(得分:1)

要么通过抓取元素来覆盖它(这里通过将this传递给函数来完成)href

<a  href="carts" onclick="addParam(this);">detail</a>
<script>

     function addParam(el)
     {
         var listId = localStorage.getItem('IDs', '');          
         window.location.href = el.href + "?id=" +listId;
     }
</script>

或将其附加到元素的href

<a  href="carts" onclick="addParam(this);">detail</a>
<script>

     function addParam(el)
     {
         var listId = localStorage.getItem('IDs', '');          
         el.href += "?id=" +listId;
     }
</script>