如何一次仅将一项附加到数组?

时间:2019-07-18 13:00:32

标签: javascript jquery html

我试图将一个元素添加到每次用户单击按钮时一次附加到HTML div的数组中。但是,每次尝试时,该元素的多个实例都会添加到数组中,并且显示的方式超出了我想要的方式。如何一次只添加一个?

var testArray = [];
var toBeAdded =
  '<div class="grid-x">' +
  '<div class="cell medium-2">' +
  "<p>Date</p>" +
  "</div>" +
  '<div class="cell medium-7">' +
  "<h4>Title</h4>" +
  "</div>" +
  '<div class="cell medium-3">' +
  "<h5>Delete</h5>" +
  "</div>" +
  "</div>";

$(".add-new-info").click(function() {
  testArray.push(toBeAdded);
  $(".info-container").append(testArray);
});

html

<div class="add-new-info">Click to add</div>
<div class="info-container"></div>

2 个答案:

答案 0 :(得分:1)

正如人们评论的那样,您要添加到数组,然后追加。

您可以尝试

var testArray = [];
var toBeAdded =
  '<div class="grid-x">' +
  '<div class="cell medium-2">' +
  "<p>Date</p>" +
  "</div>" +
  '<div class="cell medium-7">' +
  "<h4>Title</h4>" +
  "</div>" +
  '<div class="cell medium-3">' +
  "<h5>Delete</h5>" +
  "</div>" +
  "</div>";

$(".add-new-info").click(function() {
  testArray.push(toBeAdded);
  $(".info-container").append(toBeAdded);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="add-new-info">Click to add</div>
<div class="info-container"></div>

或者这个:

var testArray = [];
var toBeAdded =
  '<div class="grid-x">' +
  '<div class="cell medium-2">' +
  "<p>Date</p>" +
  "</div>" +
  '<div class="cell medium-7">' +
  "<h4>Title</h4>" +
  "</div>" +
  '<div class="cell medium-3">' +
  "<h5>Delete</h5>" +
  "</div>" +
  "</div>";

$(".add-new-info").click(function() {
  testArray.push(toBeAdded);
  $(".info-container").html(testArray);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="add-new-info">Click to add</div>
<div class="info-container"></div>

答案 1 :(得分:1)

var testArray = [];
let toBeAdded =
  `<div class="grid-x">
      <div class="cell medium-2">
          <p>Date</p>
      </div>
      <div class="cell medium-7">
          <h4>Title</h4>
      </div>
      <div class="cell medium-3">
          <h5>Delete</h5>
      </div>
   </div>`;

$(".add-new-info").click(function() {
  testArray.push(toBeAdded);
  $(".info-container").append(toBeAdded);
});

<div class="add-new-info">Click to add</div>
<div class="info-container"></div>