代码之家  ›  专栏  ›  技术社区  ›  Kawd

基于地址栏中的当前URL在HTML中定义活动链接的防错方法

  •  -1
  • Kawd  · 技术社区  · 6 年前


    它可能有查询参数,也可能没有
    它可能有一个散列或没有

    是否有一种安全/防错的JS方法通过与当前URL进行比较来检查HTML中的链接是否为“活动”链接?

    我想一些正则表达式将不得不在 <a href> 另一个在桌子上 address bar URL

    在我真正开始尝试解决方案之前,我想检查一下是否已经知道这是注定要失败的:D

    谢谢

    1 回复  |  直到 6 年前
        1
  •  1
  •   T.J. Crowder    6 年前

    是否有一种安全/防错的JS方法通过与当前URL进行比较来检查HTML中的链接是否为“活动”链接?

    这取决于是否要考虑查询参数和/或哈希。

    相对/绝对值不是问题,请使用 anchor element href protocol host 等)。锚元素包括 HTMLHyperlinkElementUtils mixin :

    interface mixin HTMLHyperlinkElementUtils {
      [CEReactions] stringifier attribute USVString href;
      readonly attribute USVString origin;
      [CEReactions] attribute USVString protocol;
      [CEReactions] attribute USVString username;
      [CEReactions] attribute USVString password;
      [CEReactions] attribute USVString host;
      [CEReactions] attribute USVString hostname;
      [CEReactions] attribute USVString port;
      [CEReactions] attribute USVString pathname;
      [CEReactions] attribute USVString search;
      [CEReactions] attribute USVString hash;
    };

    如果希望包含查询参数和哈希,则

    if (link.href === location.href)
    

    请记住,查询参数顺序可能很重要。它经常 重要,在这种情况下,对于“等效”URL,如 http://example.com?foo=a&bar=b http://example.com?bar=b&foo=a 对于该资源,如果 foo bar 这并不重要。在这种情况下,您必须解析查询参数并进行比较,以便考虑资源关于何时何地排序的规则。(例如,在大多数情况下, ?foo=1&foo=2&bar=x ?foo=2&foo=1&bar=x ?foo=1&foo=2&bar=x ?bar=x&foo=1&foo=2 ?foo=1&bar=x&foo=2 是的。但同样,这是特定于资源的。)

    location 协议 , 等)。