简体   繁体   English

jQuery函数和Ajax的最佳实践

[英]Best Practice with jquery functions and ajax

I'm new to ajax and want to best understand how to write my jQuery code so that then a page is called via ajax, my jQuery functions (simple stuff like slideshows and overlays) will still work. 我是ajax的新手,并且想最好地了解如何编写jQuery代码,以便随后通过ajax调用页面,我的jQuery函数(简单的东西,如幻灯片和叠加层)仍然可以使用。

Below is what I'm currently doing to make my jquery work on a stand alone page without ajax. 下面是我目前正在做的事情,以使我的jquery在没有ajax的独立页面上工作。

$('.microContentWrap').click(function(){

    //perform some functions

});

In order to make this same function work when this page has been loaded via ajax, I'm duplicating my code and binding it to a div called "ajax-wrapper" that loads normally on this page. 为了使该功能通过ajax加载此页面时起作用,我将复制代码并将其绑定到通常在此页面上加载的名为“ ajax-wrapper”的div上。 Without this step, the above code was not executing on the ajax page. 没有此步骤,上面的代码就不会在ajax页面上执行。

$("ajax-wrapper").on("click", ".microContentWrap", function() { 

    //exact same functions as above

});

Both of these things work, but is this the most efficient way? 这两种方法都起作用,但这是最有效的方法吗? Seems repetitive to do this two step process for every single function in my file. 对于文件中的每个功能,似乎都需要重复执行此两步过程。

$("ajax-wrapper").on("click", ".microContentWrap", function() { 

    //exact same functions as above

});

Is saying: "when I click within 'ajax-wrapper' check to see if the element I clicked is 'microContentWrap', if it is, then do this function". 是说:“当我在'ajax-wrapper'中单击时,请检查我单击的元素是否为'microContentWrap',如果是,则执行此功能。” The benefit of this approach is that 'microContentWrap' doesn't need to exist when you bind the click even listener. 这种方法的好处是,当您绑定点击甚至侦听器时,“ microContentWrap”不需要存在。

Another approach would be to add the event listener to 'microContentWrap' in your ajax callback function. 另一种方法是将事件侦听器添加到ajax回调函数中的“ microContentWrap”。 So for example: 因此,例如:

$.ajax({
    url:"getvalue.php",  
    success:function(data) {
         $('body').append('<div class="microContentWrap"></div>');
         $('.microContentWrap').click(function(){}); 
    }
  });

The solution to this was actually very simple, I just didn't understand binding. 解决这个问题的方法实际上非常简单,我只是不了解绑定。 The problem I was having was that the ajax-wrapper gets destroyed after the microContent comes in. On other non-ajax pages there was no ajax-wrapper which is why I thought there needed to be two functions. 我遇到的问题是,在microContent进入后,ajax-wrapper被破坏了。在其他非ajax页面上没有ajax-wrapper,这就是为什么我认为需要两个功能的原因。 By binding to the body, I eliminated the issue. 通过束缚身体,我消除了这个问题。

$("ajax-wrapper").on("click", ".microContentWrap", function() { 

    //exact same functions as above

});

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

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