原因
for
文中でイベントハンドラ関数を定義した場合、外のスコープの変数はイベントハンドラが実行された時の値になります。
イベントハンドラが実行されたタイミングでは for ループは終了していますので、仮に numberOfQuestions === 5
であった場合、どのチェックボタンをクリックしても下記コードのように .v4
に対してimg要素ノードが挿入されることになります。
JavaScript
1$('.v4').after('<img src=\'../img/img/img\' width=\'30\' height=\'30\'>');
問題の根本は下記スレッドが参考になると思います。
質問のコードの場合、「#check_button1 -> .v1」の相関関係が成立しますので、クリックした時に event.currentTarget.id
を元に className を算出するか、上記スレッドのようにクロージャや data-*
属性に対応する className
を閉じ込めれば解決できるでしょう。
jQuery を使っているので event.data
に閉じ込める方法も有ります。
[対策1] イベントハンドラ関数内で対象を算出する
JavaScript
1'use strict';
2jQuery('[id^="show-image-child-"').on('click', function (event) {
3 jQuery('.' + event.currentTarget.id.replace(/-child(?=-)/, '-parent')).after('<img src="../img/img/img" width="100" height="30" alt="content" />');
4});
[対策2] addEventListener の listener オブジェクトに閉じ込める
JavaScript
1'use strict';
2document.querySelectorAll('[id^="show-image-child-"').forEach(function (input) {
3 input.addEventListener('click', {
4 parent: jQuery('.' + input.id.replace(/-child(?=-)/, '-parent')),
5 handleEvent: function handleClick () {
6 this.parent.after('<img src="../img/img/img" width="100" height="30" alt="content" />');
7 }
8 }, false);
9});
[対策3] クロージャに閉じ込める
JavaScript
1'use strict';
2jQuery('[id^="show-image-child-"').each(function (i, input) {
3 var parent = jQuery('.' + input.id.replace(/-child(?=-)/, '-parent'));
4
5 jQuery(input).on('click', function () {
6 parent.after('<img src="../img/img/img" width="100" height="30" alt="content" />');
7 });
8});
[対策4] jQuery の event.data に閉じ込める
JavaScript
1'use strict';
2function handleClick (event) {
3 event.data.parent.after('<img src="../img/img/img" width="100" height="30" alt="content" />');
4}
5
6for (var i = 1; i < 6; ++i) {
7 jQuery('#show-image-child-' + i).on('click', {parent: jQuery('.show-image-parent-' + i)}, handleClick);
8}
Re: tmng さん
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/03/07 05:28 編集
2017/03/07 05:33