简体   繁体   English

如何使用jQuery遍历HTML元素和JSON?

[英]How do I loop through HTML elements and JSON with jQuery?

I'm trying to loop through all elements with the class name steem_verify, and then append " Verified" after the usernames who are verified according to my API. 我试图遍历类名称为steem_verify的所有元素,然后在根据我的API进行验证的用户名后面附加“已验证”。 I finally got it working (kind of), but after verified names it says " Verified Verified Verified", so I'm guessing my loop is messed up somewhere. 我终于让它工作了(有点),但是在经过验证的名称之后,它显示为“ Verified已验证”,因此我猜我的循环在某个地方弄乱了。

Here's my code: 这是我的代码:

$.getJSON("https://steemverify.com/api/verified.json", function (data) {
    $.each(data, function (i, item) {
        $(".steem_verify").each(function (index) {
            var username = $(this).text();
            $(data).each(function () {
                if (item.username == username) {
                    $(".steem_verify")[index].append(" Verified");
                }
            });
        });
    });
});

simply no need for first loop 完全不需要第一循环

 $.getJSON("https://steemverify.com/api/verified.json", function (data) { //$.each(data, function (i, item) { //alert(item.username); $(".steem_verify").each(function (index) { var username = $(this).text(); $(data).each(function ( i , item) { if (item.username == username) { $(".steem_verify")[index].append(" Verified"); } }); }); //}); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="steem_verify">dalt</div> <div class="steem_verify">steemitqa</div> <div class="steem_verify">steemverify</div> 

in another way you need just one loop and use .filter() so your code will looks simple like this 以另一种方式,您只需要一个循环并使用.filter()这样您的代码将看起来像这样简单

 $.getJSON("https://steemverify.com/api/verified.json", function (data) { $.each(data, function (i, item) { $(".steem_verify").filter(function(){return item.username == $(this).text() }).append(" Verified"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="steem_verify">dalt</div> <div class="steem_verify">steemitqa</div> <div class="steem_verify">steemverify</div> 

Solution by OP. 由OP解决。

This code works: 此代码有效:

$.getJSON("https://steemverify.com/api/verified.json", function (data) {
    $.each(data, function (i, item) {
        $(".steem_verify").each(function (index) {
            var username = $(this).text();
            if (item.username === username) {
                $(".steem_verify")[index].append(" Verified");
            }
        });
    });
});

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

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