简体   繁体   English

迭代DOM和JSON响应的最佳实践

[英]Best practice iterating DOM and JSON response

I'm trying to iterate the DOM and a JSON response and add a CSS class to a list item if it is on that JSON or not. 我正在尝试迭代DOM和JSON响应,并将CSS类添加到列表项(如果该列表项是否位于该JSON上)。

Here's a fiddle example , can anyone give a hand to do it properly? 这是一个小提琴的例子 ,任何人都可以帮忙正确地做这件事吗? It seems my approach is not good. 看来我的方法不好。

    $('#list li').each(function(){
         if ($(this).children().first().next().attr('child-name') == val.name[0] && ($(this).children().first().next().parent().hasClass('available') == false || $(this).children().first().next().parent().hasClass('notavailable') == false)) { 
       $(this).addClass("available");
 } else if (($(this).children().first().next().parent().hasClass('available') == false || $(this).children().first().next().parent().hasClass('notavailable') == false) && val.name[0] != "#N/A") {
       $(this).addClass("notavailable");
}
});

So, trying to add a class here: 因此,尝试在此处添加一个类:

if is not in the json 如果不在json中

<li data-id="id-4" client-id="4" class="myclass notavailable"><!-- Conent here --></li>

if is in the json 如果在json中

<li data-id="id-4" client-id="4" class="myclass available"><!-- Conent here --></li>

I think the issue comes from the nesting of the json. 我认为问题来自json的嵌套。 It seems you have a json array "clients" of 1 elements I've tried to edit your formatting of the json: 看来您有一个由1个元素组成的json数组“客户端”,我尝试过编辑json的格式:

 var response = { "clients": [ {"0":{"name":"Name 1"}, "1":{"name":"Name 2"}, "2":{"name":"Name 3"}, "3":{"name":"Name 3"} }] }; 

(If my interpretation of the json data is correct) - then you can get the data in the following way, preferably constructing an associative object array, which you can then easily reference from your dom loop: (如果我对json数据的解释是正确的)-那么您可以通过以下方式获取数据,最好构造一个关联对象数组,然后可以从dom循环中轻松引用该对象数组:

var results = new Array();

jQuery.each(response['clients'][0], function(i, val) {
    results[i] = val.name;
});

$('#list li').each(function () {
    if (results[$(this).attr("client-id")] == undefined) {
        $(this).addClass("notavailable");
    } else {
        $(this).addClass("available");
    }
});

And here is a working working jsfiddle . 这是一个工作正常的jsfiddle ( Changes only to javacript ) 仅更改为javacript


http://jsfiddle.net/awesome/3Zjw3/9/ http://jsfiddle.net/awesome/3Zjw3/9/

Two jQuery plugins which incorporate the functionality of the question specs: 两个包含问题规范功能的jQuery插件:

$(function () {

    // filters out elements that have existing specified CSS classes
    //
    // @param klass_arg [Array] CSS classes to filter
    // @return selection chain
    $.fn.filter_out_klass = function (klass_arg) {
        // raise unless klass_arg is Array
        if (Object.prototype.toString.call(klass_arg) !== '[object Array]') {
            alert('ERROR invalid klass_arg: must be Array');
        }

        // return selections after filter
        // http://api.jquery.com/filter/
        return this.filter(function () {
            $this = $(this);

            // check if any classes defined on elements
            var has_klass = false;
            $.each(klass_arg, function (i, v) {
                if ($this.hasClass(v)) {
                    has_klass = true;
                }
            });
            // return element with no class defined
            return !has_klass;
        });
    };

    // parses response and adds css classes accordingly
    //
    // @param response_arg [Object] like: JSON.parse(json_string)
    // @return selection chain
    $.fn.parse_response = function (response_arg) {
        // raise unless response_arg is Object
        if (Object.prototype.toString.call(response_arg) !== '[object Object]') {
            alert('ERROR invalid response_arg: must be Object');
        }

        // return all selections
        // https://api.jquery.com/jQuery.map/
        return this.map(function () {
            $this = $(this);

            // get client name at hash address from client-id attr
            $name = ((response_arg[$this.attr('client-id')] || {}).name || [])[0];

            // add class 'available' if child element with 'full-name' attribute is found within scope AND child el's 'full-name'-attr equals value
            if ($this.find('[full-name="' + $name + '"]').length) {
                $this.addClass('available');

            // add class 'notavailable' unless specific value: "#N/A"
            } else if ($name !== "#N/A") {
                $this.addClass('notavailable');
            }
            return $this;
        });
    };

    // json string
    $response = '{"clients":{"0":{"name":["#N/A"]},"1":{"name":["Name 2"]},"2":{"name":["Name 3"]},"3":{"name":["Name 3"]}}}';

    // parse json string to hash object and create var with clients node
    $clients = JSON.parse($response).clients;

    // init
    // filter out elements with existing classes from selection , then parse response and perform operations on selection
    $('#list li').filter_out_klass(['available', 'notavailable']).parse_response($clients);
});

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

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