RailsでjQueryのtoggle,show,hideがうまく動作しなかった
やりたいこと
rails
でjQueryを書いている時にハマったことについて共有。
やりたいことは、
ここの「回答する」ボタンをクリックすると
回答欄が表示される。これをjQuery
を使って実現する。
環境
- Ruby on Rails(5.1.5)
- Bootstrap(3.3.7)
- query-rails(4.3.1)
- ブラウザはSafari(11.0.2)とChrome(64.0.3282.186)
問題のコード
questions/show.html.erb
<h2 align="center">Title <%= @question.title %></h2>
<div class="well col-xs-8 col-xs-offset-2">
<%= simple_format(@question.description) %>
<hr>
<!-- このボタンを押すと -->
<button type="button" class="hidden-bin">回答する</button>
</div>
<!--ここを表示をトグルする-->
<div class="hidden" style="display: none">
<%= render 'answers/form' %>
</div>
question.coffee
$(document).on 'turbolinks:load', ->
$(".hidden-btn").on "click" , ->
$(".hidden").toggle()
解決策
questions/show.html.erb
<h2 align="center">Title <%= @question.title %></h2>
<div class="well col-xs-8 col-xs-offset-2">
<%= simple_format(@question.description) %>
<hr>
<!-- このボタンを押すと -->
<button type="button" class="hidden-bin">回答する</button>
</div>
<!--ここを表示をトグルする-->
<div class="hidden" style="display: none">
<%= render 'answers/form' %>
</div>
question.coffee
$(document).on 'turbolinks:load', ->
$(".hidden-btn").on "click" , ->
$(".hidden").toggle()
解決策
どうやらBootstrap
のclass="hidden"
と競合していた模様。class名をclass="hidden-form
と変えることにより解決。わかっている人にとってはとても当たり前のことかもしれないが、2時間くらい悩みました。
これを
<div class="hidden" style="display: none">
<%= render 'answers/form' %>
</div>
こうする
<div class="hidden-form" style="display: none">
<%= render 'answers/form' %>
</div>
$(document).on 'turbolinks:load', ->
$(".hidden-btn").on "click" , ->
$(".hidden-form").toggle()
Author And Source
この問題について(RailsでjQueryのtoggle,show,hideがうまく動作しなかった), 我々は、より多くの情報をここで見つけました https://qiita.com/m-dove/items/da6378b3fe0c78278c73著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .