首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >迭代DOM和JSON响应的最佳实践

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

Stack Overflow用户
提问于 2014-04-08 00:57:29
回答 2查看 231关注 0票数 1

我正在尝试迭代DOM和一个JSON响应,并将一个CSS类添加到一个列表项中,如果它是否在该JSON上。

这是一个小提琴例子,有人能帮上忙吗?看来我的方法不太好。

代码语言:javascript
复制
    $('#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");
}
});

因此,尝试在这里添加一个类:

如果不在json中

代码语言:javascript
复制
<li data-id="id-4" client-id="4" class="myclass notavailable"><!-- Conent here --></li>

如果是在json

代码语言:javascript
复制
<li data-id="id-4" client-id="4" class="myclass available"><!-- Conent here --></li>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-08 01:09:08

我认为这个问题来自于json的嵌套。您似乎有一个包含1个元素的json数组“客户端”,我试图编辑您的json格式:

var response ={“client”:{“0”:{“Name”}:“Name 1"},"1":{"name":"Name 2"},"2":{"name":"Name 3"},"3":{"name":"Name 3"} };

(如果我对json数据的解释是正确的)--那么您可以以以下方式获得数据,最好是构造一个关联对象数组,然后您可以轻松地从dom循环中引用该数组:

代码语言:javascript
复制
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");
    }
});

这是一个工作的工作小提琴。(仅更改javacript)

票数 2
EN

Stack Overflow用户

发布于 2014-04-08 02:00:47

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

包含问题规范功能的两个jQuery插件:

代码语言:javascript
复制
$(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);
});
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22925749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档