javascript - 如果动态更改 href,则无法重定向

标签 javascript jquery html css

我的 html 看起来像这样:-

<a href="http://www.google.com" id="shopall-anchor"><div class="" id="shopall-btn"></div></a>

如果我点击该按钮,它会重定向到 www.google.com(这是应该的)。 我正在尝试像这样通过 jQuery 动态更改 href :-

$('#shopall-btn').click(function() {
    $('#shopall-anchor').attr("href","www.microsoft.com");
    return false;
});

调试后我发现点击事件后 href 更改为 microsoft.com,但我无法将用户重定向到 www.microsoft.com

有什么我想念的吗?

编辑 1:-

我尝试做以下事情,但无法找到解决方案:- 1) 页面被重定向到“www.google.com”,正如下面解决方案的 anchor 标记中最初提到的那样。

$('#shopall-btn').click(function() {
    location.href = "www.microsoft.com";   
});

2) 如果我这样做,“www.microsoft.com”会附加在我当前的链接中:-

$('#shopall-btn').click(function(e) {
    e.preventDefault();       // prevents default behaviour
    $('#shopall-anchor').attr("href","www.microsoft.com");
   return true;  // activate click
});

编辑 2 :-

如果您有同样的问题并且 href 链接附加到当前 url,请检查我的回答。

最佳答案

它附加到当前 URL 的原因是因为您使用的是相对 URL,因为您没有在链接中使用 http://

$('#shopall-anchor').attr("href", "http://www.microsoft.com");

这是无效重定向的主要原因,对于其他问题,您已经有了答案:

$('#shopall-btn').click(function() {
    var newURL = "http://www.microsoft.com";
    // This will just change the href (technically of no use)
    $("#shopall-anchor").attr("href", newURL);

    // Actually redirect to the different page
    document.location.href = newURL;

    // Prevent all other navigation
    return false;
});

关于javascript - 如果动态更改 href,则无法重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39036839/

相关文章:

jquery - 如何编辑DataTable()打印标题

javascript - 使用 jQuery 在 div 中选择 <p>

java - 访问被拒绝(java.net.SocketPermission 127.0.0.1 :8080 connect, 解析)

javascript - 在Drupal 7基本页面中插入PHP代码

javascript - 替换字符串中的所有 <p></p> 标签

html - 不显示 Jade 的 Bootstrap 导航栏

html - 如何在 tvOS 自定义应用程序中包含基于 HTML5 的游戏?

javascript - 使用循环生成表行时自动将行和列数据添加在一起

javascript - LocalStorage 无法在 IE 11 Win 8.1 上运行

javascript - 多次显示同一图像。使用 JQuery 一次只更改一个