简体   繁体   English

通过AJAX加载页面时jQuery无法正常工作

[英]jQuery not working when page loaded via AJAX

I have an index page that has jQuery loaded as well as a js file for a slider plugin. 我有一个已加载jQuery的索引页以及一个滑块插件的js文件。 Then I'm using an on click event to use .load to load an external page, like this: 然后,我使用on click事件使用.load加载外部页面,如下所示:

//jQuery loaded from Google CDN here (in head)

jQuery( document ).ready(function() {
    jQuery( ".button" ).click(function() {
        var myUrl = "/url-to-page";
        jQuery( "#target-div" ).load(myUrl);
    });
});

This successfully loads the external page into #target-div, but the jQuery loaded on the index page does not fire on elements loaded from the external page. 这样可以成功将外部页面加载到#target-div中,但是在索引页面上加载的jQuery不会在从外部页面加载的元素上触发。 For example, I have some images (for the slider plugin) on the external page, but the slider plugin doesn't turn them into a slideshow as it would if I put those same images (inside a wrapper div) onto the index page directly. 例如,我在外部页面上有一些图像(用于Slider插件),但是与直接将相同的图像(在包装div内)放置到索引页面上一样,Slider插件不会将它们变成幻灯片显示。 。

The external page does not any html, head, or body tags--only the content I want to load wrapped in some divs. 外部页面没有任何html,head或body标签-只是我要加载的内容包装在某些div中。

Does anyone know the "trick" to making jQuery work on an externally loaded page? 有谁知道使jQuery在外部加载的页面上工作的“技巧”?

The issue is your click event has already been bound. 问题是您的点击事件已被绑定。 You will need to bind the click events to the newly created elements on your page after they have been loaded. 你会需要它们已经被加载后,结合自己的网页上点击事件到新创建的元素。 Jquery's load method takes a function as a second parameter. jQuery的load方法将一个函数作为第二个参数。 It is fired once the load is complete. 加载完成后便会触发。

jQuery( document ).ready(function() {
    jQuery( ".button" ).click(function() {
        var myUrl = "/url-to-page";
        jQuery( "#target-div" ).load(myUrl, function () {
          // bind events here
        });
    });
});

edit: using event delegation 编辑:使用事件委托

$(function () {    //shorthand for document ready
    $('#target-div').on('click', '.button', function () {
        $("#target-div").load("/url-to-page");
    });
});

Every .button within #target-div will have the click event bound to it. #target-div每个.button都将绑定有click事件。 The click event will also be bound to every .button element added to #target-div . click事件还将绑定到添加到#target-div每个.button元素。 Hope this helped. 希望这会有所帮助。

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

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