在JSON数据中添加HTML元素



以下是使用JSONLint验证的JSON数据:

[{
"text": "Products",
"data": {},
"children": [{
    "text": "Fruit",
    "data": {
        "price": "",
        "quantity": "",
        "AddItem": "+",
        "RemoveItem": "&#215"
    },
    "children": [{
        "text": "Apple",
        "data": {
            "price": 0.1,
            "quantity": 20,
            "AddItem": "+",
            "RemoveItem": "&#215"
        }
    }, {
        "text": "Strawberry",
        "data": {
            "price": 0.15,
            "quantity": 32,
            "AddItem": "+",
            "RemoveItem": "& #215"
        }
    }],
    "state": {
        "opened": false
    }
}, {
    "text": "Vegetables",
    "data": {
        "price": "",
        "quantity": "",
        "AddItem": "&# 43;",
        "RemoveItem": "&#215"
    },
    "children": [{
        "text": "Aubergine",
        "data": {
            "price": 0.5,
            "quantity": 8,
            "AddItem": "+",
            "RemoveItem": "&#215"
        }
    }, {
        "text": "Cauliflower",
        "data": {
            "price": 0.45,
            "quantity": 18,
            "AddItem": "+",
            "RemoveItem": "&#215"
        }
    }, {
        "text": "Potato",
        "data": {
            "price": 0.2,
            "quantity": 38,
            "AddItem": "+",
            "RemoveItem": "&#215"
        }
    }]
}],
"state": {
    "opened": false
}
}]

我要找的是将键AddItemRemoveItem的值转换为HTML按钮

上面的JSON将用于在jsTree插件中渲染节点。

jsFiddle链接,我将使用这个json数据。基本上,我想用相同的

按钮替换+-符号。

有人有解决这个问题的方法吗?

编辑1:我在几个地方读到直接在JSON数据中添加HTML元素是不可取的,因为它可以在代码中的许多地方使用,每次它可能有不同的HTML。如果有人有更好的方法,那就太好了。

我从未使用过jsTree插件,可能有更好的方法来解决你的问题,但这似乎是我认为你在寻找的。只需将此添加到代码末尾即可。

$(document).on('click','.jstree-table-wrapper', function() {//insted of document i would used jtrees containing div
    $.each($('.jstree-table-cell span'),function(){
        if($(this).html()=='+'){      
            $(this).html('<button class="addBtn">+</button>')
        }else if($(this).html()=='×'){      
            $(this).html('<button class="removeBtn">x</button>')
        }
    });
});
$(document).on('click','.addBtn',function(){//insted of document i would used jtrees containing div
     var id = 'j1_'+$(this).parent().parent().attr('id').split('_')[2];
     demo_create(id);
     $('.jstree-table-wrapper').trigger('click');
});
$(document).on('click','.removeBtn',function(){//insted of document i would used jtrees containing div
     var id = 'j1_'+$(this).parent().parent().attr('id').split('_')[2];
     demo_delete(id);//you might need to work on your delete function
     $('.jstree-table-wrapper').trigger('click');
});

最新更新