代码之家  ›  专栏  ›  技术社区  ›  Brig Lamoreaux

如何通过JavaScript在锚定标记中导航href

  •  7
  • Brig Lamoreaux  · 技术社区  · 17 年前

    有没有一种简单的方法让JavaScript模拟用户单击页面上的锚定标记?这意味着需要设置推荐人Url。仅设置document.location.href不会设置引用者Url。

    <script>
      $(document).ready(function () {
        $("a").click();
    });
    </script>
    
    <a href="http://example.com">Go here</a>
    

    5 回复  |  直到 17 年前
        1
  •  14
  •   Paolo Bergantino    17 年前

    你可以做:

    window.location = $("a").attr("href");
    

    var href = $('a').attr('href');
    $('<form>').attr({action: href, method: 'GET'}).appendTo($('body')).submit();
    

    这是一个黑客程序,但适用于所有浏览器。

        2
  •  2
  •   Pang Ajmal PraveeN    8 年前
    document.location.href = "#wanted_Location";
    
        3
  •  1
  •   Svante Svenson    17 年前

    也许这就是你要找的?

    $(document).ready(function () {
      $("a").each(function(){
        if($(this).click()){
          document.location.href = $(this).attr("href");
        }
      });
    });
    
        4
  •  1
  •   Gaurav Gandhi    9 年前

    有一个更简单的方法来实现它,

    HTML

    <a href="https://getbootstrap.com/" id="fooLinkID">Bootstrap is life </a>
    

    // Simulating click after 3 seconds
    setTimeout(function(){
      document.getElementById('fooLinkID').click();
    }, 3 * 1000);
    

    使用纯javascript模拟单击。

    您可以在上查看工作示例 jsFiddle .

        5
  •  0
  •   Svante Svenson    17 年前

    好的,referer没有使用document.location(根据我的另一个回答)进行设置,可能与window.navigate(url)一起使用?如果这不起作用,那么下面的方法可能会很糟糕,尽管这很难看:

    $(function() {
      $("a").each(function(){
        if($(this).click()){
          $('<form method="get" action="' + $(this).attr("href") + '"></form>').appendTo("body").submit();
          return false;
        }
      });
    });