Javascript追加不断添加元素

时间:2017-07-17 13:46:47

标签: javascript jquery

每次点击sponsorListTree li时,我都会尝试追加list[i].name and list[i].email次。我可以附加 document.getElementById("name").appendChild(div_group); ,但是当我点击div几次时会出现问题,相同的数据会加起来而不是只显示一次结果

$.ajax({
            url: 'test.php',
            method: 'GET',
            success: function(data){             
                var list = data;
                for (i = 0; i < list.length; i++) { 
                $('#sponsorListTree li').attr('id', function(i) {
                    return 'sponsorListTree'+(i+1);
                });
                $('#sponsorListTree').append('<li class="button"><a href="#myModal" id= "investor" data-toggle="modal" >'+list[i].name+'<br/> <table class="data"><tbody><tr><td><span id="information" class="details"><br/><br/> '+ 'Email: ' + list[i].email + '</br></br> '+ 'Contact No: ' + list[i].contact.phone + ' </br></br> '+ 'Joined date: '  + list[i].date + ' </br> </br>'+  'InvestedAmount: ' + list[i].account.investedAmount + '</span></td></tr></tbody><table></a></li>');

                }
                $("#sponsorListTree li").click(function() {
                    var name = $(this)[0].innerHTML;
                    var details = $(this).find('span')[0].innerHTML     
                    var div_name = document.createElement('div');
                    var div_details = document.createElement('div');
                    div_name.innerHTML = name;
                    div_details.innerHTML = details;
                    div_name.className ="nameDetail";
                    div_details.className ="detail";                    
                    var div_group = document.createElement('div');
                    div_group.append(div_name);
                    div_group.append(div_details);
                    document.getElementById("name").append(div_group);  
                }); 

                $(".button").click(function() {
                    $("span").toggleClass("details");
                });

            }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul style=" overflow-x: auto; width: 400%; height: 600px;">
        <li>
            <a id="root" href="#"></a>
            <ul id ="sponsorListTree">
            </ul>
        </li>
</ul>
<div id = "name" class="control-label"></div>

0 个答案:

没有答案