再次点击javascript按钮时,数据会重复

时间:2017-11-03 19:11:01

标签: javascript jquery html

我能够显示所有数据,但当我再次点击我的团队时,数据会显示两次。一次又一次地单击意味着显示数据的次数。如何显示一次数据?我的意思是只有6名队员,没有6名队员重复。

  function myFunction() {
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");

    var data1 = "TEAMSEARCH";
    $.ajax({
      url: 'TeamAssignment',
      type: 'POST',
      data: {
        data1: data1
      },
      success: function(result) {
        var memberList = $.parseJSON(result);
        for (var i = 0; i < memberList.length; i++) {
          console.log(memberList[i].fullName);
          document.getElementById("demo").innerHTML += '<li style="list-style:none;">' + memberList[i].fullName + '</li>';
        }
      }
    });
  }
  <div class="col-lg-3 mb-0" style="display: flex;align-items: center;">
    <div class="popup" onclick="myFunction()">
      <h6>My team</h6>
      <span class="popuptext" id="myPopup">My team members:<br><h7 id="demo"></h7><br></span>
    </div>
  </div>
</div>
<ol class="breadcrumb"></ol>

1 个答案:

答案 0 :(得分:1)

在开始for循环之前,您需要清除 demo 元素:

success: function(result) {
    var memberList = $.parseJSON(result);
    document.getElementById("demo").innerHTML = '';
    for (var i = 0; i < memberList.length; i++) {
          console.log(memberList[i].fullName);
          document.getElementById("demo").innerHTML += '<li style="list-style:none;">' + memberList[i].fullName + '</li>';
        }
    }

就个人而言,在使用jquery时,我更喜欢使用代码:

$.ajax({
    url: 'TeamAssignment',
    type: 'POST',
    data: {
        data1: data1
    },
    dataType: "json",
    success: function(memberList) {
        $("#demo").html('');
        for (var i = 0; i < memberList.length; i++) {
            console.log(memberList[i].fullName);
            $("#demo").append('<li style="list-style:none;">' + memberList[i].fullName + '</li>');
        }
    }
});