【问题标题】:Redirect to (currenturl)/example.html onclick with JavaScript使用 JavaScript 重定向到 (currenturl)/example.html onclick
【发布时间】:2016-10-13 22:57:27
【问题描述】:

当您单击按钮时,我正在尝试将我的位置从“currentUrl”更改为“currentUrl/somePage.html”。

代码不依赖于硬编码的 url,这一点很重要。相反,它应该抓取用户所在的当前 url,并将 '/somePage.html' 的值附加到它的末尾。

我做了一些查找,发现 window.location.href 会返回我当前的 url 位置,并且 window.location 会将我重定向到一个新的位置。但是,当我尝试将它们放在一起时,单击按钮时出现“未定义功能”错误。

我的代码看起来像这样......

HTML:

<button class="btn btn-default" onclick="redirectToPage()">Some Page</button>

JS:

$(function () {

    function redirectToPage() {
        var url = window.location.href;
        window.location(url + "/somePage.html");
    }
});

你们都是美丽的人!感谢您的帮助!

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    如果你打算使用 jQuery,那么你应该使用它的所有功能:

    (我永远不会推荐内联 javascript)

    html:

    <button class="btn btn-default js-do-redirect">Some Page</button>
    

    jQuery:

    $(document).ready(function(){
      $('.js-do-redirect').on('click', function(){
        var url = window.location.href;
        window.location = url + "/somePage.html";
      });
    });
    

    或者如果你想让它可重复使用:

    html:

    <button class="btn btn-default js-do-redirect" data-redirect-to="/somePage.html">
      Some Page
    </button>
    

    jQuery:

    $(document).ready(function(){
      $('.js-do-redirect').on('click', function(){
        var url = window.location.href;
        var page = $(this).data('redirect-to');
        window.location = url + page;
      });
    });
    

    推荐阅读Decoupling Your HTML, CSS, and JavaScript

    【讨论】:

    • 太棒了!谢谢!
    【解决方案2】:

    你已经接近了。 window.location 不是一个函数,而是一个属性。

    function redirectToPage() {
        var url = window.location.href;
        window.location = url + "/somePage.html";
    }
    

    【讨论】:

      【解决方案3】:

      redirectToPage 仅在处理函数的范围内定义。你需要把它移到外面。

      【讨论】:

        【解决方案4】:

        您的问题是范围界定。 要么删除 $(function(){}) jQuery 闭包,要么使用 jQuery 在带有 $('#someid').click() 的按钮上创建 onClick 事件。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多