递归JQuery Load命令 [英] Recursive JQuery Load command

查看:91
本文介绍了递归JQuery Load命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JQuery将内容加载到div元素中,并且一切正常.

I am using JQuery to load content into a div element and everything is working ok.

$("#content").load('www.urltogetcontentfor.com')

我现在想扩展一下.我的结构是一棵树的结构,其中每个分支可能(或可能不)具有附加到其上的子分支.我想发生的事情是递归调用JQuery load命令,直到没有附加子级为止.类似于以下步骤:

I now want to extend this. The structure I have is that of a tree where each branch may (or may not) have child branches attached to it. What I want to happen is that the JQuery load command is recursively called until there are no children attached to it. Something like the following steps:

  1. 调用Jquery加载函数以将内容加载到内容" div中.
  2. 如果load函数返回子级已附加
  3. 再次调用JQuery加载函数以获取子项
  4. 重复步骤2和3,直到没有孩子可用为止.

有人在JQuery中做到了这一点,还是知道一个可以处理此问题的插件?

Has anyone done this in JQuery or know of a plug in which handles this?

谢谢

推荐答案

可以按照以下原则递归加载内容:

Loading content recursively could be done with this principle:

function loadTree($element) {
  $element.each(function(){
    this.load('url', function(){
      loadTree(this.find('.children'));
    });
  });
}

loadTree($('#content'));

您使用jQuery对象调用该函数.它循环遍历对象中的元素,并为每个元素调用load.在成功回调中,它在已加载的代码中选择子代并自行调用.

You call the function with a jQuery object. It loops through the elements in the object and calls load for each. In the success callback it picks the children in the loaded code and calls itself.

但是,如果可能的话,您应该尝试使用一个请求来获取整个树,例如将数据作为JSON返回并从中创建元素.

However, if possible you should try to get the entire tree using one request, for example returning the data as JSON and create elements from that.

这篇关于递归JQuery Load命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆