window.location.href不起作用

问题描述 投票:14回答:4

我的网站是http://www.collegeanswerz.com/。我正在使用rails。该代码用于搜索大学。我希望用户能够输入大学名称,单击输入,然后转到网址,而不是查看搜索结果(如果用户正确输入名称。如果不是,我想显示搜索结果) 。我正在使用“a”和“stackoverflow.com”作为占位符,而我试图让它工作。

我正在使用window.location.href基于此:How to redirect to another webpage in JavaScript/jQuery?

JavaScript的

$("#search_text").submit(function() {
    if ($("#search_field").val() == "a")
    {
        window.location.href = "http://stackoverflow.com";
        alert('worked');
    }
});

布局文件

<%= form_tag("/search", :method => 'get', :id => 'search_text', :class => 'form_search') do -%> 
    <div id="search"> <%= search_field_tag :search, params[:search], :placeholder => 'enter college', :id => "search_field", :class => 'input-medium search-query' %></div> 
<% end -%>

static_pages_controller.rb

def search
  @colleges = College.search(params[:search])
end

警报正在运行,它告诉我if语句中的内容应该被执行。但它带我到正常的搜索结果而不是stackoverflow.com。为什么是这样?

jquery ruby-on-rails window.location
4个回答
38
投票

代码运行后,浏览器仍在提交表单。

return false;添加到处理程序以防止这种情况发生。


2
投票

试试这个

`var url = "http://stackoverflow.com";    
$(location).attr('href',url);`

或者你可以做这样的事情

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

并在函数调用结束时添加一个返回false


1
投票

请检查您是否正在使用//而不是\\,如下所示

Wrong:"http:\\stackoverflow.com"

Right:"http://stackoverflow.com"

0
投票

HTML5引入了history.pushState()history.replaceState()方法,允许您分别添加和修改历史条目。据我所知,您可以使用pushState函数,如下面的代码来解决您的问题。

history.pushState(null, null, "http://stackoverflow.com")

有关处理这类问题的HTML5新功能的更多信息可用here

© www.soinside.com 2019 - 2024. All rights reserved.