简体   繁体   English

通过ajax在jQuery中加载页面的麻烦

[英]trouble with loading a page in jquery via ajax

I am loading a page into a div via the jquery load function. 我通过jquery加载功能将页面加载到div中。 The actual loading part is fine. 实际的加载部分很好。 The code looks basically like this: 该代码基本上如下所示:

$("div#loadhere").load("newfile.html?" + new Date().getTime());

In newfile.html I have a series of divs, and I have code that (for testing) sends an alert when a div is clicked. 在newfile.html中,我具有一系列的div,并且具有(用于测试)单击div时发送警报的代码。 That's fine too. 也可以

The problem is this: when I load a page into div#loadhere and then choose a different page to load into the same div, the alert message happens twice. 问题是这样的:当我将页面加载到div#loadhere中,然后选择另一个页面加载到同一div中时,警报消息会发生两次。 If I load yet another page, it happens three times. 如果我加载另一个页面,则会发生三次。

In other words, it seems like jquery (or the DOM) doesn't realize that the previous loads have gone away. 换句话说,jquery(或DOM)似乎没有意识到以前的负载已经消失。

Thanks very much in advance for any help! 非常感谢您的任何帮助!

If I'm not mistaken, you need to use the jQuery unbind to unbind the event. 如果我没有记错的话,则需要使用jQuery unbind来取消绑定该事件。

unbind 解除绑定

Here's a similar question on stackoverflow 这是关于stackoverflow的类似问题

Try .delegate() - http://api.jquery.com/delegate/ 尝试.delegate() - http://api.jquery.com/delegate/

You can bind the event handler to the 'body' or a similar, top-level div, and watch for events targeting your desired div. 您可以将事件处理程序绑定到“ body”或类似的顶级div,并监视针对您所需div的事件。 The example given on the docs site is for a table: docs网站上给出的示例是针对一个表的:

$("table").delegate("td", "hover", function(){
    $(this).toggleClass("hover");
});

This way avoids the multiple binds issue you are encountering. 这样可以避免您遇到的多重绑定问题。

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

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