jquery 複数の要素に同じイベントを設定する

jquery 複数の要素に同じイベントを設定する

jqueryで、複数の要素に同じイベントを設定するサンプルコードを記述してます。「カンマ区切り」で「要素」を指定してます。

環境

  • OS windows10 pro 64bit
  • jquery 3.6.0
  • Apache 2.4.43
  • ブラウザ chrome 91.0.4472.77

複数の要素に同じイベントを設定

複数の要素に同じイベントを設定するには「カンマ区切り」で「要素」を指定します。

$("要素を指定,要素を指定").on('click', function() {})

以下は、2つの「実行」ボタンをクリックして、実行した方のボタンの「id名」を取得して表示するサンプルコードを記述してます。

※デザインは「semantic-ui」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- semantic.css  -->
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>
<style>
  body>.grid {
    height: 100%;
  }

  .fields {
    margin-top: 5px;
  }
</style>
<script>

$(function() {

  $('#btn,#btn2').on('click', function() {

    $('#lab').text( `${$(this).attr('id')}から実行されました` )
    
  })
  
})

</script>

<body>

  <div class="ui middle aligned center aligned grid">
    <div class="column">

      <a id="lab" class="ui teal tag label">label</a>

      <div class="ui stackable fields">
        <button id="btn" class="ui green basic button">実行</button>
        <button id="btn2" class="ui green basic button">実行2</button>
      </div>

    </div>
  </div>
</body>

</html>

取得されていることが確認できます。