2016-04-13 6 views
1

私は以前の ".on" jqueryハンドラを使って、追加したアンカーのクリックを確認しました。jQuery:.appendで追加され、.onで処理されたhtml要素からparamを取得する方法?

$('#selector-to-thing-that-exists').on('click', '.thing-that-will-be-added-later', function() { 
    //I want to get the "data-pointnumber" and "data-goodanswer" on the clicked element. 
}); 

ここでの問題は、$(これは)私に$(「#セレクターツー事-ことが-存在」)及びませんクリックした要素を(それはリンクです)を得ていることです。 十分明確ですか?

$.each(this.currentQuestion.Reponse,function (arrayID,rep) { 
    $('#QuestionContainerSingle').find('.liste-boutons').append('<li><a href="" class="button-big btn-rep" data-nbpoints="'+rep.NbPoints+'" data-bonne="'+rep.Bonne+'">'+rep.Texte+'</a></li>'); 
}); 
$('#QuestionContainerSingle').on('click','.btn-rep',function (e) { 
    e.preventDefault(); 
    console.log($(this).attr('data-nbpoints')); 
}); 

ここはhtmlです...より大きなアプリケーションの一部であるため、この質問に必要なものを抽出するのは簡単ではありません。

<div class="question-content" id="QuestionContainerSingle"> 
      <div class="header-question"> 
       <p class="intitule"> 

       </p> 
      </div> 
      <div class="content"> 
       <div class="title-box">Find the best answer</div> 
       <ul class="liste-boutons"> 

       </ul> 
      </div> 
     </div> 
+0

$(これ)は、セレクタが存在するクラスではなく、「これから追加されるクラス」となります。 clickとfunction()の間で渡される余分なパラメータは、基本的には#selector-to-thing-that-existsの中のターゲット要素です。また、htmlを追加することができれば、それは正確な問題を見つけるのに役立ちます – DinoMyte

+0

私はいくつかのHTMLで私の質問を編集し、私のJSを少し変更しています...私はまだ$(これ)私に ".btn-rep"というクリックされた要素を返さないでください。ちょうど "e.target"が私に良い要素を返すことに注意してください! – Dantahoua

答えて

0

最後に、私は犯人を見つける!私はthis.btnRep = $( '.btn-rep');を使用します。私のアプリのinitで。 私が使用するとき

$('#QuestionContainerSingle').on('click',**this.btnRep**,function (e) { 
    e.preventDefault(); 
    console.log($(this).attr('data-nbpoints')); 
}); 

それは機能しません。 しかし、私はそれが働いて

$('#QuestionContainerSingle').on('click',**'.btn-rep'**,function (e) 

... スタンジェを使用するときに!

+1

セレクタの中にオブジェクトを渡しているため、第1のケースで機能しないのはなぜですか。 jqueryセレクタはオブジェクトではなく文字列値でのみ動作します – DinoMyte

関連する問題