Ajax加载页面中的Jquery不起作用

Ajax加载页面中的Jquery不起作用,ajax,jquery,Ajax,Jquery,当我使用 $('body').html(data1) 或 在AJAX中,任何HTML标记或jQuery函数都不能在加载的页面上工作 $.ajax({ type:"GET", dataType: 'html', url: 'hell.php', success : function(data1) { alert(data1);// will alert "ok" $('body').html(data1); }, });

当我使用

$('body').html(data1)

在AJAX中,任何HTML标记或jQuery函数都不能在加载的页面上工作

$.ajax({
    type:"GET",
    dataType: 'html',
    url: 'hell.php',
    success : function(data1) {
        alert(data1);// will alert "ok"
        $('body').html(data1);
    },
});

您在$('body').html(data1)之前附加的事件将不会触发,因为先前在body中的元素将不再存在


您必须重新附加事件,或者使用方法直接将事件附加到文档。

在附加事件处理程序时,最好使用
jQuery
live
函数。
请看:

你的问题不多,但我可以试一试

首先,定义要附加到函数中加载元素的功能,例如:

function attachEventsAfterAjax(){

    $('.aLoadedElement').on('click', function(){
        console.log('Yay!');
        return false;
    });

}
$.ajax({
    [...],
    success: function(data){

        // Don't replace the <body> HTML, that's not a good idea
        // $('body').html(data);

        $('#container').html(data);

        // Now attach the functionality!
        attachEventsAfterAjax();

    }
});
然后,在加载新内容后,调用该函数,例如:

function attachEventsAfterAjax(){

    $('.aLoadedElement').on('click', function(){
        console.log('Yay!');
        return false;
    });

}
$.ajax({
    [...],
    success: function(data){

        // Don't replace the <body> HTML, that's not a good idea
        // $('body').html(data);

        $('#container').html(data);

        // Now attach the functionality!
        attachEventsAfterAjax();

    }
});
$.ajax({
[...],
成功:功能(数据){
//不要替换HTML,这不是一个好主意
//$('body').html(数据);
$('#container').html(数据);
//现在附加功能!
attachEventsAfterAjax();
}
});

希望这有帮助

所以AJAX调用可以正常工作,只是新加载的元素上的jQuery不能正常工作,对吗?你能发布你的事件处理程序吗?@prytsh请详细说明你的问题。什么是正文和html?它们是ID吗?
.live()
不久前就被弃用了,取而代之的是
.on()
&
.delegate()
,这取决于具体情况
.on()
不会总是将功能附加到加载的元素。加载代码时,您应该“惰性地”附加功能。为什么不在加载之前附加动态加载的html本身上的事件?是的,最好在ajax调用成功后附加事件,但有时它们太多了。在这种情况下,如果有点“重”,那么.on()也应该起作用。