【问题标题】:Replacing a jstree node on ajax call在ajax调用上替换jstree节点
【发布时间】:2013-05-20 17:31:11
【问题描述】:

我有一个用于存储数据的 jstree 对象,我使用 ajax 一步一步地完成它。我调用了一个 ajax.php 文件,该文件将返回 HTML 格式的节点,具体取决于我发送给它的数据。

我的问题如下:我知道我将收到的数据已经包含当前节点的结构,而不是用它从 ajax 调用接收到的数据替换当前节点,jstree 将结构添加到当前节点作为一个新儿子,这不是我想要的。

例如,如果我点击节点 1:

0
| - 1
| - 2

我会得到以下结构:

0
| - 1
| | - 1
| | | - 1.1
| | | - 1.2
| - 2

我无法更改 ajax 调用返回,但是我认为使用以下代码可能会出现一些小故障,以用返回的数据替换节点,而不是将其作为当前节点的子节点插入:

$node.jstree({
    "plugins" : [ "themes", "html_data" ],
    "html_data" : {
        ajax: {
            url: "ajax.php",
            data: function(node){
                return {
                    index:  (node != -1) ? node.attr("id") : 0
                };
            },
            type: "POST"
        }
    },
    animated: 'fast'
});

非常感谢您的回答:)

【问题讨论】:

    标签: javascript jquery replace jstree


    【解决方案1】:

    好吧,所以在与 jstree 插件斗争并被我的一个朋友建议改变视角之后,我最终决定从头开始制作我自己的折叠/展开树算法,毕竟这并不难使用 jQuery 和 CSS,即使是像我这样的 JavaScript 新手! 我花了一天的时间,但我学得很好...

    jQuery:

    $('.closed').on('click', changeContent);
    function changeContent(e) {
        $('.open').unbind();
        $('.closed2').unbind();
        $('.closed').unbind();
        var $this = $(this);
        $this.attr('class', 'open');
        $.ajax({
            type: 'post',
            url: 'ajax.php',
            data: {
                index: $this.attr("id")
            },
            success: function(xhr,msg) {
                $this.replaceWith(xhr);
                $('.closed').on('click', changeContent);
                UpdateOpen();
            }
        });
    }
    
    function UpdateOpen(e) {
        $('.open').unbind();
        $('.closed2').unbind();
        $('.open, .closed2').on('click', function(e) {
            e.stopPropagation();
            $('.open').unbind();
            $('.closed2').unbind();
            var $this = $(e.currentTarget);
            if($this.attr('class') == 'closed2') {
                $this.attr('class', 'open');
                $this.children('ul').show();
                UpdateOpen(e);
            } else if($this.attr('class') == 'open') {
                $this.attr('class', 'closed2');
                $this.children('ul').hide();
                UpdateOpen(e);
            }
        });
    }
    

    CSS:

    .closed {padding-left: 7px; list-style-type: none; background: URL("/img/plus.gif") left top no-repeat; }
    .closed2 {padding-left: 7px; list-style-type: none; border-left: 1px dotted; background: URL("/img/plus.gif") left top no-repeat; }
    .open {padding-left: 7px; list-style-type: none; border-left: 1px dotted; background: URL("/img/minus.gif") left top no-repeat; }
    

    我知道这不是最好的实现,但这就是我对 JavaScript 的了解。请注意此代码取决于 ajax.php 返回数据的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多