2016-11-25 8 views
-6

に私は私のページ内のボタンを取り扱うクリックでこのコードを使用しています:

$(document).on("click", $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection"), function (e) { 
     addItemToDocumentGrid(); 
     $('#removeDocumentFromSection').disable(true).addClass("disabled"); 
     $('#removeSelection').disable(true).addClass("disabled"); 
}); 

しかし、イベントが発生するなどすぐに私はページのどこかをクリックします。 $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection")で選択したいと思われるボタンではない場合でも。

$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection")は、実際に選択したいボタンである要素を返します。

なぜこのように動作しますか?

答えて

0

document要素にonClickイベントを添付しています。試してみてください:あなたはイベントの委任を使用する場合は、2番目の引数はセレクタ、ないjQueryオブジェクトでなければなりません

var button = $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection"); 
button.on("click", function() { 
    addItemToDocumentGrid(); 
    $('#removeDocumentFromSection').disable(true).addClass("disabled"); 
    $('#removeSelection').disable(true).addClass("disabled"); 
}); 
+0

これに関する下落は厳しいようです。私たちは、OPがイベント委任を使用することを望んでいるのか分からず、OPはセレクターが関連する要素を見つけ出すと言う。それは、何が間違っていて、それを修正するかの両方を示しています。 –

+0

バランスをとってupvoted: '$()。find()'が働いているので、この回答を与えるイベント委任の必要はないと思われます。 –

7

$(document).on("click", '#' + GlobalVariables.currentUserType + " .addDocumentToSection", function (e) { 
// ---------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
     addItemToDocumentGrid(); 
     $('#removeDocumentFromSection').disable(true).addClass("disabled"); 
     $('#removeSelection').disable(true).addClass("disabled"); 
}); 

あなたはイベントの委任を使用しない場合、あなたは上のイベントをフックする要素にonを呼び出す必要があります。これは、すべてのthe on documentationで覆われている

$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection").on("click", function (e) { 
     addItemToDocumentGrid(); 
     $('#removeDocumentFromSection').disable(true).addClass("disabled"); 
     $('#removeSelection').disable(true).addClass("disabled"); 
}); 

+0

30代後4投票。読まずに投票する? –

+2

@TânNguyễn:または人々は高速に読む。もしあなたがその概念に精通しているなら、上記を読むのに10-15秒を要しません。 –

+0

@TânNguyễnまた可能性があります:質問を読んでいる人、明白な答えを見る、回答を追加する、回答が追加されたという通知を受け取る、それが正確に何を入れるかを確認する、 –

-1
$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection").on("click", function(e){ 

}); 

jQueryは.on("click"の前にセレクタを使用できますが、これはうまくいくはずです。

関連する問題