2013-08-31 57 views
0

在我的rails應用程序中,我試圖爲搜索按鈕添加jquery焦點效果。當鼠標在該按鈕上時,它應該改變顏色。但jQuery代碼不工作,雖然我嘗試使用search.js,search.js.erb。在gems文件中,我還包括jquery rails在Gem文件中,並且還嘗試了bundle安裝。在rails中包含jquery 3

<!DOCTYPE html> 
<html> 

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> 
    </script> 
    <script> 
     $(document).ready(function(){ 
     $("text_field_tag").focus(function(){ 
     $(this).css("background-color","#cccccc"); 
     }); 
     $("text_field_tag").blur(function(){ 
     $(this).css("background-color", "#ffffff"); 
     }); 
     }); 
    </script> 
    <body> 
     <%=form_tag({controller: 'tweets', action:'index'}, method: "get") do %> 
     <%=label_tag(:search, "Search for:") %> 
     <%=text_field_tag(:text) %> 
     <%=label_tag(:show, "Show for:") %> 
     <%=text_field_tag(:show) %> 
     <%= submit_tag("GO") %> 
     <% end %> 
    </body> 

</html> 

我還通過刪除「腳本SRC」標籤即使在當時它不是working.Anybody請幫助..

回答

0

你做了一個小錯誤嘗試,但不要擔心。照我下面的建議去做。
1)給出text_field_tag的id,如<%= text_field_tag(:show,'',:id =>'show_fld')%>
2)獲取該id並將其保存爲jQuery函數中的DOM。像

<script> 
    $(document).ready(function(){ 
    $("#show_fld").focus(function(){ 
     $(this).css("background-color","#cccccc"); 
    }); 
    $("#show_fld").blur(function(){ 
     $(this).css("background-color", "#ffffff"); 
    }); 
    }); 
</script> 

現在上述將工作。

+0

如何我的文件是否應該命名爲search.js.erb? – user2492854

+0

'$('#element_id')'是你如何在jQuery中選擇元素。你的jquery代碼是錯誤的,而不是文件名 – ragnika

+0

試圖也沒有工作..我收到錯誤「缺少模板鳴叫/搜索,應用程序/搜索與{:語言環境=> [:恩],:格式=> [: html:,::handlers => [:erb,:builder,:coffee]}。搜索:*「/ home/niranjan/tweetsblog7/app/views」。我應該修改som其他文件還是包含其他文件? – user2492854

0

如果您使用的是導軌3,則可以使用鏈輪來包含您需要的一切。

  • 添加gem 'query-rails'至資產組你的Gemfile的
  • 同時添加//= require jquery//= require jquery_ujs您的application.js文件
  • 確保您application.html.erb文件還包括<%= javascript_include_tag "application" %>