单击时为每个按钮添加/删除div

时间:2018-03-26 21:16:36

标签: javascript jquery append

我尝试使用append为每个按钮提供自己的div(.modal-item),可以在.modal容器内创建和删除单击按钮。每个.item都有自己的按钮,内部嵌套了不同的内容。

我需要的是一个例子:如果我点击标有Btn 1的按钮,我想在.modal-item内创建一个包含内容的.modal div来自Btn 1 .item。如果我再次点击Btn 1,则会将其删除。每个按钮也是如此。

按钮应作为checkbox用于创建和删除.modal-items。换句话说,每个.modal-item的添加/删除都由它的按钮处理。



$(function() {
  $('#btn').click(function() {
    var newDiv = $('<div class="modal-item"><h4><a>Dynamic Title</a></h4> </div>');
    $('.modal').append(newDiv);
  });
});
&#13;
.container {
  display: flex;
  border: 1px solid blue;
}

.item,
.modal-item {
  width: 100px;
  border: 1px solid;
}

.modal {
  display: flex;
  border: 1px solid green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="item">
    <button id="btn">Btn 1</button>
    <h4> Test 1 </h4>
    <div class="subtitle"> Title 1 </div>
    <div class="info"> This is Info / Description 1. </div>
  </div>
  <div class="item">
    <button id="btn">Btn 2</button>
    <h4> Test 2 </h4>
    <div class="subtitle"> Title 2 </div>
    <div class="info"> This is Info / Description 2. </div>
  </div>
  <div class="item">
    <button id="btn">Btn 3</button>
    <h4> Test 3 </h4>
    <div class="subtitle"> Title 3 </div>
    <div class="info"> This is Info / Description 3. </div>
  </div>
</div>
<div class="modal"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

第一名:ID必须是唯一的,因此您需要将id="btn"更改为class="btn"

第二名:为每个btn使用data属性并将其传递给模态项div,可以完成

$(function() {
  $('.btn').click(function() {
    var newDiv = $('<div data-btn="'+$(this).attr("data-btn")+'" class="modal-item"><h4><a>Dynamic Title'+ ($(this).closest('.item').index() + 1) +'</a></h4> </div>');
    if($('.modal .modal-item[data-btn="'+$(this).attr("data-btn")+'"]').length < 1 ){
      $('.modal').append(newDiv);
    }else{
      $('.modal .modal-item[data-btn="'+$(this).attr("data-btn")+'"]').remove();
    }
  });
});
.container {
  display: flex;
  border: 1px solid blue;
}

.item,
.modal-item {
  width: 100px;
  border: 1px solid;
}

.modal {
  display: flex;
  border: 1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="item">
    <button class="btn" data-btn="btn1">Btn 1</button>
    <h4> Test 1 </h4>
    <div class="subtitle"> Title 1 </div>
    <div class="info"> This is Info / Description 1. </div>
  </div>
  <div class="item">
    <button class="btn" data-btn="btn2">Btn 2</button>
    <h4> Test 2 </h4>
    <div class="subtitle"> Title 2 </div>
    <div class="info"> This is Info / Description 2. </div>
  </div>
  <div class="item">
    <button class="btn" data-btn="btn3">Btn 3</button>
    <h4> Test 3 </h4>
    <div class="subtitle"> Title 3 </div>
    <div class="info"> This is Info / Description 3. </div>
  </div>
</div>
<div class="modal"></div>