LoginSignup
1
2

More than 1 year has passed since last update.

【Stimulus】Stimulusをクリックした要素を取得する方法

Last updated at Posted at 2022-04-11

はじめに

Rails7 でデフォルトでインストールされるようになった Stimulus でクリックした要素を取得する方法を忘備録として残しておきます。

環境

Rails 7.0.2
Ruby 3.1.1
Stimulus-rails 1.0.4

取得方法

ボタンが4つあり特定のボタンをクリックした時だけ、アクションを発動させる時、通常ならdata-targetを利用することで javascript 側で要素を取得できます。
ですが、それが使えないときはStimulusのメソッドの引数を利用することで取得できます。

html

button.html
<div data-controller='button'>
  <button id='1' data-action='click->button#next'>
    1
  </button>
  <button id='2' data-action='click->button#next'>
    2
  </button>
  <button id='3' data-action='click->button#next'>
    3
  </button>
  <button id='4' data-action='click->button#next'>
    4
  </button>
</div>

javascript

メソッドの引数のcurrentTargetにクリックした要素が入っています。

button_controller.js
import { Controller} from '@hotwired/stimulus';

export default class extends Controller {

  next(event) {
    const button_id = event.currentTarget.id;
    if (button_id == 1) {
      console.log(button_id)
    }
  }
}

参考

やっぱり困った時は、公式サイトのリファレンスを見るのが一番です。

公式サイト

1
2
0

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
1
2