设置location.href无法从<a> click</a>开始工作

时间:2012-09-04 16:35:07

标签: javascript

这是我从一位离开的同事那里接过的代码:

<input type="text" class="value" placeholder="0"></span><br>
<a href="/model/act/id/'.$model->id.'" class="act act-a" url="/model/act/id/'.$model->id.'">Act Now</a>

<script>
    $('.act-a').click(function(){
        if(parseInt($('.value').val())>0){
            //window.location.href = window.location.origin + $(this).attr('url') + '?r=' + parseInt($('.value').val());
            window.location.replace("www.google.com");
            return true;
        }
        return false;
    });
</script>

当我点击该链接时,我从未被重定向到www.google.com。最初我想要的是执行注释代码,但是设置www.google.com进行调试,我想要意识到我的重定向被忽略了,而是使用了原来的href!

如何在点击链接时设置window.location.href,添加GET参数?

2 个答案:

答案 0 :(得分:2)

在window.location之后将reutrn更改为true以返回false;

$('.act-a').click(function(){
    if(parseInt($('.value').val())>0){
        //window.location.href = window.location.origin + $(this).attr('url') + '?r=' + parseInt($('.value').val());
        window.location.replace("www.google.com");
        return false;
    }
    return false;
});

在点击,提交等事件上返回false会阻止此类事件的默认行为。只有当你想要运行一个函数然后让事件传播到其他常规的监听器,例如跟随一个链接的href,继续正常的表单提交等等时,才使用return true ...这篇文章对于事件冒泡基础有用:{{3} }

答案 1 :(得分:2)

return true;告诉浏览器执行链接的默认操作。因此,浏览器会关注该链接,而不是运行window.location

删除两个return语句,然后添加e.preventDefault();

$('.act-a').click(function(e){
    e.preventDefault();
    if(parseInt($('.value').val(), 10) > 0){
        window.location.href = window.location.origin + $(this).attr('url') + '?r=' + parseInt($('.value').val(), 10);
    }
});

P.S。您应该将,10添加到parseInt,以确保将该号码解析为基数10.