zoukankan      html  css  js  c++  java
  • 在循环中创建网页元素的问题

    for (var i = 0; i < json.length; i++) {
        var topic = json[i];
        var btn = $('<button>');
        btn.addClass('btn btn-primary');
        btn.attr('type', 'button');
        btn.html(topic.topicComment);
        $.getJSON('action.action', {
            topicId : topic.p2pTopicId
        }, function(res) {
            var jsn = $.parseJSON(res);
            var cnt = parseInt(jsn);
            if (cnt > 0) {
                btn.removeClass('btn-default').addClass('btn-primary');
            } else {
                btn.removeClass('btn-primary').addClass('btn-default');
            }
        });
        $('#hrAfterBtn').before(btn);
    }

    这样创建是有问题的,其中的$.getJSON会在所有的循环都结束之后才调用,

    这样其中的btn对象就是循环结束之后的最后的那个btn对象;

    需要将其中的创建过程提炼成一个函数:

    for (var i = 0; i < json.length; i++) {
        var topic = json[i];
        createMsgButton(topic);
    }
    function createMsgButton(topic) {
        var btn = $('<button>');
        //...   
    }
  • 相关阅读:
    博雅机器学习十讲1
    tensorflow学习笔记1
    卓有成效的程序员3
    卓有成效的程序员2
    卓有成效的程序员1
    探索需求6
    数据预处理
    数据科学介绍
    探索需求5
    探索需求4
  • 原文地址:https://www.cnblogs.com/stono/p/4271484.html
Copyright © 2011-2022 走看看