简体   繁体   English

对于每个范围数据,请获取ID并从JSON响应中检查ID

[英]For each span data get id and check id from json response

I'm trying to check any id sending with ajax and response json getting the id from json then checking if there is an id into span and then add it but is not working is always adding and adding more and more 我正在尝试检查使用ajax发送的任何id和响应json从json获取id,然后检查是否有一个id插入span,然后将其添加,但不起作用,总是在添加越来越多的东西

Jquery jQuery的

e.results.forEach(function(e) {
    var name = e.name;
    var id = e.id;
    if ($(".visitors span").length) {
        $('.visitors span').each(function() {
            var data_id = $(this).attr('data-id');
            if (data_id != id) {
                $(".visitors").append("<span data-id='" + id + "'>" + name + "</span>");
            }
        });
    } else {
        $(".visitors").append("<span data-id='" + id + "'>" + name + "</span>");
    }
});

Although I think your code is correct, but a suggestion: Instead of looping through the spans you're appending, just check if a span with a data-id exists (using CSS Attribute-Equal Selector ), if not append a new span like this: 虽然我认为您的代码是正确的,但是有一个建议:与其循环遍历您要附加的跨度,不如检查是否存在具有data-id的跨度(使用CSS Attribute-Equal Selector ),如果不附加新的跨度,例如这个:

e.results.forEach(function(e) {
    var name = e.name;
    var id = e.id;

    var $span = $(".visitors span[data-id = '" + id + "']"); // select all the spans that have the data-id equal to id
    if (!$span.length) { // if there is none
        $(".visitors").append("<span data-id='" + id + "'>" + name + "</span>"); // then add a new one
    }
});

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

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