设置一个jQuery的事件处理程序的AJAX加载的数据加载、事件、程序、数据

2023-09-10 16:24:14 作者:七重人格

作为相当新的jQuery和AJAX的基础知识,我一直在试图建立一些相当简单的动态加载。

Being fairly new to jQuery and the AJAX basics, I've been trying to set up some fairly simple dynamic loading.

我有一个.js文件设置click事件处理程序,它看起来是这样的:

I include a .js file setting up the click event handler, and it looks like this:

var baseurl = document.getElementById("baseurl").getAttribute("href");
var pattern = new RegExp("[^/]+");
var page = "cnt/" + pattern.exec(window.location.href.substr(baseurl.length)) + ".php";

$(document).ready(function(){
    $('a.ajax').bind('click',function(event){
        event.preventDefault();
        $('#content').load("cnt/" + pattern.exec(this.href.substr(baseurl.length)) + ".php")
    })
});

请注意,我做了一些更改该文件因此相对HREF测试/将变成一个绝对路径文件CNT / testing.php。

Note that I do some changes to the file so the relative href "testing/" would turn into an absolute path to the file "cnt/testing.php".

我的锚标签是这样的:

<a href="testing/" class="ajax">Link to testing page</a>

我的问题是,每当新的内容加载到DIV#内容处理程序在我的js文件是不是可能已经使用AJAX出现的任何链接注册。 换句话说,链接将简单地充当普通锚标记。我希望它加载使用AJAX下一个页面,就像它的第一页。

My problem is, that whenever new content is loaded into div#content the handler in my .js file is not registered for any links that may have appeared using AJAX. In other words the links will simply act as ordinary anchor-tags. I want it to load the next page using AJAX, just like it does with the first page.

推荐答案

如果要插入新的内容,这些内容是动态的,事件处理程序只能绑定到实际存在的元素。您需要将事件委托给存在于您要将事件处理程序的时间DOM更高的元素。我将使用该文档,您将使用最近的非动态母公司委派到:

If you're inserting new content, that content would be dynamic, and the event handler can only be bound to elements that actually exist. You need to delegate the event to an element higher in the DOM that exists at the time you are attaching the event handler. I'll use the document, you'll use the closest non dynamic parent to delegate to :

$(document).on('click', '.ajax', function(event){
    event.preventDefault();
    $('#content').load("cnt/" + pattern.exec(this.href.substr(baseurl.length)) + ".php")
});