0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

子要素にcheckboxを持つ要素に実装したjQueryのclickイベントが2回発生する

Last updated at Posted at 2020-04-02

以下のようなcheckboxとそれに紐付くlabelを子要素としてもつ要素にjQueryでclickイベントを実装すると
label上をクリックした際にイベントが2回重複して発生します。

html
<div id="box">
  <input type="checkbox" id="chekbox">
  <label for="checkbox">checkbox</label>
</div>
js
let count = 1;
$("#box").on("click", function(){
  console.log(count+ " clicked");
  count ++;
});
console(クリック後)
> 1 clicked
> 2 clicked

これはそもそもlabelがクリックされた時にlabelに紐付くinputもクリックされたとみなされるために起こるそうなので、
クリック対象をinputに向けることで解決する。

js
$("#box input").on("click", function(){
   // クリック後にしたい処理
});

animal_chara_computer_penguin.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?