window.location.href不起作用

时间:2013-08-18 15:24:11

标签: jquery ruby-on-rails window.location

我的网站是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。这是为什么?

5 个答案:

答案 0 :(得分:38)

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

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

答案 1 :(得分: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

答案 2 :(得分:1)

请检查您是否误用了//而非\\,如下所示

Wrong:"http:\\stackoverflow.com"

Right:"http://stackoverflow.com"

答案 3 :(得分:0)

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

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

here提供了有关处理此类问题的HTML5新功能的更多信息。

答案 4 :(得分:0)

即使在使用return false;之后仍然遇到问题。然后使用以下内容。

setTimeout(function(){document.location.href = "index.php"},500);
相关问题