0
0

More than 3 years have passed since last update.

jQueryを使ってクリックする度に要素のテキストを切り替える方法

Last updated at Posted at 2021-08-24

今回の記事

①jQueryを使ってクリックする度に要素のテキストを切り替える方法をメモ
※自分の,そのままのコードを貼り付けているので、分かりづらいかもしれません。

おまけ
② ①で切り替えると他の要素を変更させる方法
Railsにて、要素を変えたいが中身にインスタンス変数などがあり、ややこしいかも

環境

ruby 2.6

対象のコード

①jQueryを使ってクリックする度に要素のテキストを切り替える方法

HTML
 <p class = "footer-left-m" >Monthly</p>

こちらは、期間の月を表してます。こちらをクリックするたび「Yearly、Day、Week」に変更していく。

application.html.erb
 <script src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

jQueryを読み込みさせる。

jQuer
<script>

      $('.footer-left-m').on('click', function () {
        if ($(this).text() === '▷Monthly') {
              $(this).text('▷Yearly');
            } else if ($(this).text() === '▷Yearly'){
               $(this).text('▷Day');
            } else if ($(this).text() === '▷Day'){
              $(this).text('▷Week');
            }else{
              $(this).text('▷Monthly');
            }
      });

    </script>

body内に記述
ポイント:$('.footer-left-m') は、class = "footer-left-m"を指定。先頭に「.」がついている

こちらでクリックするたび、「Monthly,Yearly、Day、Week」の順に変更してます。
▷はつけなくて大丈夫です!

以上

おまけ

 ①で切り替えると他の要素を変更させる方法
今回は期間を変わるたび金額を変えたかったです。
表示内容に、DBから情報をひっぱてきていた内容を変更させたかったので、期間が変わるたびテキストではなくて、別のhtmlを表示させるようにしました。

HTML
<div class = "footer-light" id ="footer-light">
    <p class ="totale-price"  ><%= "¥#{number_to_currency(@content.sum(:price))}" %></p>
</div>

こちらはユーザーが登録したアイテムの合計金額。
「<%= "¥#{number_to_currency(@content.sum(:price))}" %>」の部分はMonthlyの金額が表示されてる。
やりたいことは、期間が変わるたび、別のhtmlを表示させて金額を変える。

jQuer
<script>

      $('.footer-left-m').on('click', function () {

        if ($(this).text() === '▷Monthly') {
              $(this).text('▷Yearly');
              $('#footer-light').html("<%= escape_javascript(render 'price.y') %>");        
            } else if ($(this).text() === '▷Yearly'){
               $(this).text('▷Day');
              $('#footer-light').html("<%= escape_javascript(render 'price.d') %>");
            } else if ($(this).text() === '▷Day'){
              $(this).text('▷Week');
              $('#footer-light').html("<%= escape_javascript(render 'price.w') %>");
            }else{
              $(this).text('▷Monthly');
              $('#footer-light').html("<%= escape_javascript(render 'price.m') %>");
            }

      });

    </script>

_price.y.html.erb
<p class ="totale-price" id ="t-price" ><%= "¥#{@content.sum(:price)*12}" %></p>

ポイント: ('#totale-price')は IDを指定。クラス指定の ('.footer-light')でも問題ない
.html("<%= escape_javascript(render 'price.y') %>"); で、Yearlyに期間が変わったらテンプレートを呼び出して別のHTML(_price.y.html.erb)に差し替え

以上になります。
最後までありがとうございました。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0