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

Unable to redirect if href is changed dynamically

本文关键字:重定向 href 动态 如果      更新时间:2023-09-26

我的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",正如下面解决方案最初在锚标记中提到的。

$('#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;
});

您可以使用location.href。在jQuery

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

<script type="text/javascript">
document.getElementById("shopall-btn").onclick = function () {
    location.href = "www.microsoft.com"; 
};

$('#shopall-btn').click(function() {
    $('#shopall-anchor').attr("href","www.microsoft.com");
    //return false;//remove it,it stops the event propagation
});

我用下面的代码解决了这个问题。

<!-- <a id="shopall-anchor"> -->
<div class="" id="shopall-btn"></div>
<!-- </a> -->

。完全删除锚标记。

和按钮上绑定的click事件,像这样:-

$('#shopall-btn').click(function(e) {
    document.location.href='http://www.pipabella.com';
});

希望能帮到别人。

编辑1:-

或者,如果你想使用锚标记,也可以这样做:-

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

可以使用以下代码

jQuery jQuery库
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

然后是HTML代码

<a href="javascript:void(0)"> <div class="" id="shopall-btn"></div></a>

这是jQuery代码

<script type="text/javascript">
    $('#shopall-btn').click(function(e) {
    window.location.href='http://www.microsoft.com';
   });
</script>

希望对你有帮助