【问题标题】:If I click a link I want to get QUERY STRING of it [duplicate]如果我点击一个链接,我想得到它的查询字符串[重复]
【发布时间】:2019-06-11 19:51:10
【问题描述】:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $('a').attr('onclick', 'window.location.href=hideref(this.href); return false;');
    function hideref(strUrl){
    return "https://test.xyz/?q="+escape(strUrl);
    }
    </script>

这是我的代码 如果我点击

&lt;a href="https://example.com/post/1"&gt;link 1&lt;/a&gt;

然后会是这样的

https://test.xyz/?q=https%3A//example.com/post/1

但我希望它像

https://test.xyz/?q=/post/1

我该怎么做?

【问题讨论】:

  • 你不应该使用 attr 来设置事件监听器
  • 另外 /post/1 不是查询字符串。查询字符串是 ? 之后的内容
  • 哦,对不起,那我怎么能用英语称呼那个 /post/1 东西呢?
  • /post/1是url的路径(见en.wikipedia.org/wiki/URL#Syntax

标签: javascript jquery html


【解决方案1】:

您应该使用this.pathname (source),而不是使用this.href 将url 发送到hideref 函数。

您的代码如下所示:

<script type="text/javascript">
    $('a').click(function() {
      window.location.href = hideref(this.pathname + this.search);
      return false;
    });
    function hideref(strUrl){
        return "https://test.xyz/?q="+escape(strUrl);
    }
</script>

【讨论】:

  • 非常感谢!!!这很好用!!!!
  • 不客气,如果对您有帮助,您可以将我的回答标记为已接受;)
  • 如果我想发送 /wpwp/wp.php 之类的东西?q=ddddddd 我该如何更改 this.pathname
  • 我已经更新了代码,您需要添加this.search 以便在结果中同时获得路径名和查询字符串。
  • 感谢您的帮助!
【解决方案2】:

如果您只想要 url 中的路径名,则从您单击的锚点中引用路径名。您也不应该使用属性来定义点击处理程序。

$('a').on('click', function (evt) {
  evt.preventDefault()
  var path = hideref(this.pathname);
  console.log(path);
  //window.location.href = path;
});

function hideref(strUrl) {
  return "https://example.com/?q=" + encodeURIComponent(strUrl);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://example.com/post/1">link 1</a>

【讨论】:

    【解决方案3】:

    你需要

    • 分配点击处理程序
    • preventDefault 停止链接
    • 获取路径名并搜索
    • 编码

    $('a').on('click',function(e) {
      e.preventDefault(); // stop the link
      var newUrl = "https://test.xyz/?q="+encodeURIComponent(this.pathname+this.search); 
      console.log(newUrl); // delete this and uncomment next line
      // window.location=newUrl;
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <a href="https://example.com/post/1">link 1</a>
    <a href="https://example.com/post/1?bla=bla1">link 2</a>

    【讨论】:

      猜你喜欢
      • 2013-11-12
      • 1970-01-01
      • 2014-11-19
      • 2018-09-20
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      相关资源
      最近更新 更多