【问题标题】:jQuery - Iterating JSON Object To Find ElementjQuery - 迭代 JSON 对象以查找元素
【发布时间】:2015-05-03 06:26:38
【问题描述】:

情况:

我有动态 json 对象数据,需要用它来查找元素。

例子:

[ 
  { "tag": "article",
    "id": "post-316",
    "order": "0" },
  { "tag": "div",
    "class": "entry-content",
    "order": "0" } 
]

它的长度、键和值可以根据用户要求随时更改。

我需要使用该数据在网页中动态查找指定元素。第一组字符串是父元素的数据,用于初始化搜索,最后一组是目标子元素。

目的:

所以,从上面的 json 示例中,我想找到一个元素:

类名 entry-content, tag name div, index 0 在父类内部 post-316

通过以这种格式转换该 json 数据,或者可能更简单或更好:

// because the parent already have attribute id, so no need to check other info of this element    
var elem = $("#post-316").find(".entry-content");

if(elem.prop("tagName") == "div" ) {
   elem.css("background", "#990000");
}

进展:

我尝试使用 jquery $.each() 方法,但无法找到实现该目的的方法。

这是我目前坚持的代码:

var json = $.parseJSON(theJSONData);
$.each(json, function(i, e){
    $.each(e, function(key, data){
        alert(i + " " + key + " " + data);
        if(json.length - i == 1) {
            alert("target " + data);
        }
        if(json.length - i == json.length) {
            alert("parent " + data);
        }
    }
    );
});

问题:

  • 是否有可能使用迭代从那种 JSON 数据中实现 PURPOSE

  • 如果可以,怎么做?

  • 如果没有,我可以使用什么方式?

【问题讨论】:

    标签: javascript jquery json find element


    【解决方案1】:

    您可以使用一种格式,以便脚本知道要获取什么:

    var data = {
        'id': '#',
        'class': '.'
    };
    
    var json = JSON.parse(theJSONData);
    $.each(json, function (a) {
        $.each(data, function (b) {
            if (a[b]) {
                $(data[b] + a[b])[+a['order']]; // Element
            }
        });
    });
    

    如果你确定你得到的数据是(因为它是类,或者数据,它会有一个标签名)

    var json = JSON.parse(theJSONData),
        last = document;
    $.each(json, function (a) {
        var selector = (a['id']) ? '#'+a['id'] : '.'+a['class'];
    
        last = $(last).find(a['tag']+selector)[+a['order']]; // Element
    });
    

    【讨论】:

    • 如何动态使用这种元素查找器格式的数据:$("#post-316").find(".entry-content");
    猜你喜欢
    • 2011-05-13
    • 2011-06-05
    • 1970-01-01
    • 2011-09-12
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    相关资源
    最近更新 更多