LoginSignup
0
0

More than 3 years have passed since last update.

jQuery on() と click()の違いについて

Last updated at Posted at 2020-04-19

clickイベントを使用するときに、.on()と.click()があるので、違いを分かりやすくまとめました。

index.html
<input type="button" id="hoge" value="button">
script.js
 $(function(){

      // 新しい要素の追加
      $('#generate').click(function(){
        $('#hoge').after('<input type="button" id="hogehoge" value="click">');
      });

      // clickされた時の処理①
      $('#hogehoge').click(function(){
        alert('click!!');
      });

      // clickされた時の処理②
      $(document).on('click', '#hogehoge', function(){
        alert('on!!');
      });

    });

②の方はクリックしても無効らしい。

click() : ページロード時に存在する要素にイベントを付与して、その後動的に追加されたものには有効でない。
on() : ページロード時後、動的に追加された要素にもイベント付与してくれる

多少コードが長くなったとしてもon()を使ったほうがエラーの危険性は少なそう。

0
0
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
0
0