【问题标题】:Persisting URL query string with jQuery breaks anchors使用 jQuery 持久化 URL 查询字符串会破坏锚点
【发布时间】:2015-02-24 10:46:35
【问题描述】:

我使用以下 jQuery 脚本在我的整个网站上保留某个查询字符串。但是,它会破坏 html 锚点,因为一旦调用了 html 锚点链接,它就会再次将字符串附加到 URL

示例:

预期行为:www.example.com/?string=value ---> www.example.com/?string=value#anchor

实际结果:www.example.com/?string=value ---> www.example.com/?string=value#anchor?string=value

function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

jQuery(document).ready(function ($) {
var persistedQueryParam = getParameterByName('STRINGNAME');

if (persistedQueryParam && persistedQueryParam.length > 0) {
$('a[href]').each(function () {
  var elem = $(this);
  var href = elem.attr('href');
  elem.attr('href', href + (href.indexOf('?') != -1 ? '&' : '?') + 'STRINGNAME=' + persistedQueryParam);
});
}
});

对此有任何解决方案吗?我尝试通过 href.indexOf('#') 检查哈希,但无法正常工作。似乎我无法检查 URL,因为单击时添加了锚点。

【问题讨论】:

    标签: jquery anchor query-string


    【解决方案1】:

    我想出了一个解决方案:问题是,html 锚点也在 href 中。我通过排除以#开头的链接解决了这个问题:

    $('a[href]').not('a[href^="#"]').each
    

    这意味着,但是,包含 url 和锚点的链接(如 www.example.com/page#anchor)会加载页面,但不会跳转到锚点。不过,与我无关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      相关资源
      最近更新 更多