7

ajaxリクエストでhtmlページをリロードした後、共通のjsファイルがあります。このファイルの関数、 $(document).ready(function()間の共通のJS関数に アクセスできません。それらにアクセスして共通ファイルの関数を起動するにはどうすればよいですか

一般的な JS :

  $(document).ready(function() { 

 $(".agree_btn").click(function(){
        alert(123);             
    });

});

phtmlページの関数

$('.loadMoreAnswers').live('click', function(event) {

          var location_id = $(this).attr('location_id');
          var counter= $(this).attr('counter');
                $('#loadingAnswer').show();

        $.ajax({
            type: 'POST',
            url: '/daleel/loadmore',
            data: 'location_id='+location_id+'&part='+'answers'+'&answerCounter='+counter,  //with the page number as a parameter
            success: function(msg){

                if(msg.length!=0)    //if no errors
                { $(this).parent().load("view")
                    $('#loadingAnswer').remove();
                    counter+=5;
                    $('#profile-page-answer').append(msg); 

                } 
                else $("#loadingAnswer").remove();

            },
            dataType: 'html'
        });

              });

HTML を次のようにレンダリングします。

<a agreed="no" agreed-content-id="63066" class="agree_btn" id="agree-a63066">
Agree
    </a>

しかし、このリンクをクリックすると、Common JS ファイルの関数が実行されません

4

3 に答える 3

8

ajaxの成功でクリックイベントハンドラーを再バインドする

success: function(msg){
 //your code
 $(".agree_btn").bind('click');
}

delegateまたは、1.7より前のjQueryバージョンに使用できます。

$(document).delegate(".agree_btn",'click',function(e){
 //your code
});

または、jQueryバージョン1.7以降のuseonメソッドを使用しています

$(document).on("click",".agree_btn",function(e){
 //your code
});

.live非推奨のドキュメントは使用しないでください

jQuery 1.7以降、.live()メソッドは非推奨になりました。.on()を使用して、イベントハンドラーをアタッチします。古いバージョンのjQueryのユーザーは、.live()ではなく.delegate()を使用する必要があります。

于 2012-04-30T07:42:01.497 に答える
0

live()共通の js ファイル内で使用します。例えば

$('selector').click(function(){
//function body
})

この使用の代わりに

$('selector').live('click', function(){
//function body
})
于 2012-04-30T07:33:04.817 に答える
-1

ajax の完了後に document.ready 関数を埋め込みます。ajax 呼び出しの後、ページにスクリプトを再登録します。

例えば:

$.ajax({
            url: 'deleteEntry',
            data: {'ids': JSON.stringify(getList)},
            async: true,
            success: function (data) {
                location.reload();
            },
            error: function (data) {
                alert('error');
            },
            complete: function (data) {
                //add your script in body here
            }
        });
于 2013-03-27T12:31:35.773 に答える