简体   繁体   English

jQuery没有处理AJAX加载的html内容

[英]jQuery not working on AJAX loaded html content

I have a PHP admin dashboard in which am using bootstrap theme. 我有一个PHP管理仪表板,其中使用了bootstrap主题。 We know it have inbuilt jQuery objects like drop-down menu, collapse, tabs, etc., And it all will work if we just added bootstrap js file. 我们知道它有内置的jQuery对象,如下拉菜单,折叠,制表符等等。如果我们刚刚添加了bootstrap js文件,它们都可以工作。

Now the problem is when I get contents from ajax call and display it on my page, all javascript controls which loaded via ajax are not working. 现在问题是当我从ajax调用获取内容并将其显示在我的页面上时,通过ajax加载的所有javascript控件都无法正常工作。

Am using this ajax call for all my inner pages display. 我使用这个ajax调用显示所有内页。 So it may have any bootstrap javascript control on loaded HTML. 所以它可能对加载的HTML有任何bootstrap javascript控件。

So how can I fix this dynamically on every ajax call. 那么如何在每个ajax调用上动态修复此问题。 My ajax loading javascript is below 我的ajax加载javascript在下面

$('a').bind('click',function(event){
    event.preventDefault();
    $.get(this.href,{},function(response){
        $('#app-content-body').html(response)
    });
});

Note : My problem is not in my above code. 注意:我的问题不在上面的代码中。 Actual problem is bootstrap javascript controls not working when I load html content from above code 当我从上面的代码加载html内容时,实际问题是bootstrap javascript控件无法正常工作

jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. jQuery在运行时只知道页面中的元素,因此添加到DOM的新元素无法被jQuery识别。 To combat that use event delegation , bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. 为了解决这种使用事件委托问题 ,将新添加的项目中的事件冒泡到jQuery在页面加载时运行时在DOM中的某个点。 Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. 许多人使用document作为捕获冒泡事件的地方,但没有必要在DOM树上高高举起。 Ideally you should delegate to the nearest parent that exists at the time of page load. 理想情况下, 您应该委托给页面加载时存在的最近的父级。

Change your click event to use on() , provided your version of jQuery supports it; 如果您的jQuery版本支持,请将您的click事件更改为on() ;

$(document).on('click', 'a', function(event){

If you're using jQuery older than version 1.7 use delegate() : 如果您使用的是早于1.7版的jQu​​ery,请使用delegate()

$('body').delegate('a' , 'click', function() {

Note the operator order, they are different with on() reading a little more logically. 注意操作员顺序,它们与on()读取不同的逻辑更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM