window.location.href 不起作用 [英] window.location.href not working

查看:75
本文介绍了window.location.href 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站是 http://www.collegeanswerz.com/.我正在使用导轨.该代码用于搜索大学.我希望用户能够输入大学名称,点击回车,然后被带到 url,而不是看到搜索结果(如果用户正确输入名称.如果没有,我想显示搜索结果).我在尝试让它工作时使用a"和stackoverflow.com"作为占位符.

My website is http://www.collegeanswerz.com/. I'm using rails. The code is for searching for colleges. I want the user to be able to type in the colleges name, click enter, and be taken to the url, rather than seeing the search results (if the user types in the name properly. if not I want to show the search results). I'm using "a" and "stackoverflow.com" as placeholders while I try to get it to work.

我使用 window.location.href 基于这个:如何在 JavaScript/jQuery 中重定向到另一个网页?

I'm using window.location.href based on this: 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

static_pages_controller.rb

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

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

The alert is working, which tells me that the things inside the if statement should be being executed. But it's taking me to the normal search results instead of stackoverflow.com. Why is this?

推荐答案

在您的代码运行后,浏览器仍在提交表单.

The browser is still submitting the form after your code runs.

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

Add return false; to the handler to prevent that.

这篇关于window.location.href 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆