【问题标题】:JS - Remove elementJS - 移除元素
【发布时间】:2021-04-06 14:19:08
【问题描述】:

所以我的页面中已经有了这些元素:

<button id="addMore" class="button" style="background-color: green;">+</button>
<button id="removeMore" class="button" style="background-color: red;">-</button>
<div id="fieldList">
       
       <select style="width:100%" id="prisplan" name="prisplan[]" required>
           <option selected value="">Velg prisplan</option>
           <?php foreach($eachlines as $lines){ //add php code here
           echo "<option value='".$lines."'>$lines</option>";
           }?>
        </select>
        
        <input type="text" name="gsm[]" placeholder="GSM" required onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
      
    </div>

当按下 + 按钮时,它会添加新元素。这非常有效:

$(function() {
  $("#addMore").click(function(e) {
    e.preventDefault();
    
    // Get the element of prisplan
    var itm = document.getElementById("prisplan");
    // Copy the element and its child nodes
    var cln = itm.cloneNode(true);
    // Append the cloned element to list
    document.getElementById("fieldList").appendChild(cln);
    
    $("#fieldList").append("<input type='text' placeholder='GSM' name='gsm[]' required onkeypress='return event.charCode >= 48 && event.charCode <= 57'>");
    
    });
});

现在我还想要一个删除按钮。该按钮应该从“addMore”按钮中删除最后添加的元素,但永远不要删除原始元素。我怎样才能做到这一点?下面的代码是我到目前为止所得到的,但这会删除所有内容。

$(function() {
  $("#removeMore").click(function(e) {
    e.preventDefault();
    
    $('#fieldList').remove();

    });
});

我怎样才能做到这一点?

【问题讨论】:

  • 为什么不在每个新输入字段旁边添加一个删除按钮?
  • 为新添加的按钮添加一个类或一些属性,然后删除它的最后一次出现
  • @Mr.Polywhirl 你的意思是在$("#removeMore").click(function(e) {中加一个吗?
  • 这个问题可能会有所帮助:stackoverflow.com/questions/39638935/jquery-undo-append
  • @AndreaSeliz 看看我的回答,可能是您正在寻找的解决方案。

标签: javascript html


【解决方案1】:

只需为select 标记和input 标记添加一个容器。所以你在删除一组元素时会有更多的控制权

$(function () {
  $('#addMore').click(function (e) {
    e.preventDefault();
    // Get the element of prisplan
    var itm = document.getElementsByClassName('my-container')[0];

    // Copy the element and its child nodes
    var cln = itm.cloneNode(true);

    // Remove input of cloned element
    cln.removeChild(cln.lastElementChild);

    // Append the cloned element to list
    document.getElementById('fieldList').appendChild(cln);

    $('.my-container:last-child').append(
      `<input type='text' placeholder='GSM' name='gsm[]' required onkeypress='return event.charCode >= 48 && event.charCode <= 57'>`
    );
  });

  $('#removeMore').click(function (e) {
    e.preventDefault();

    const containers = $('.my-container');

    // Remove last added containers, leave only 1 original container
    if (containers.length > 1) $('.my-container:last-child').remove();
  });
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<button id="addMore" class="button" style="background-color: green">+</button>
<button id="removeMore" class="button" style="background-color: red">-</button>
<div id="fieldList">
  <div class="my-container">
    <select style="width: 100%" id="prisplan" name="prisplan[]" required>
      <option selected value="">Velg prisplan</option>
      <option value='".$lines."'>$lines</option>
    </select>

    <input
      type="text"
      name="gsm[]"
      placeholder="GSM"
      required
      onkeypress="return event.charCode >= 48 && event.charCode <= 57"
    />
  </div>
</div>

编码愉快!

【讨论】:

    【解决方案2】:

    这是一个工作示例,但您的代码中有一些非常糟糕的做法,例如,您的文档中绝不能有 ID 的副本,而是尝试使用类。这就是为什么我将 id='prisplan' 编辑为 class='prisplan' 但工作尚未完成,您可以看到删除选择后输入仍然存在。要解决这个最简单的方法是将选择和输入包装在一个带有类的 div 中,并在按下按钮时将其连同其内容一起删除

    $(function() {
      $("#addMore").click(function(e) {
        e.preventDefault();
        
        // Get the element of prisplan
        var itm = document.getElementsByClassName("prisplan")[0];
        // Copy the element and its child nodes
        var cln = itm.cloneNode(true);
        // Append the cloned element to list
        document.getElementById("fieldList").appendChild(cln);
        
        $("#fieldList").append("<input type='text' placeholder='GSM' name='gsm[]' required onkeypress='return event.charCode >= 48 && event.charCode <= 57'>");
        
        });
        $("#removeMore").click(function(e) {
        e.preventDefault();
        let allSelects = document.getElementsByClassName("prisplan")
        document.getElementsByClassName("prisplan")[allSelects.length -1].remove();
    
        })
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="addMore" class="button" style="background-color: green;">+</button>
    <button id="removeMore" class="button" style="background-color: red;">-</button>
    <div id="fieldList">
           
           <select style="width:100%" class="prisplan" name="prisplan[]" required>
               <option selected value="">Velg prisplan</option>
               <?php foreach($eachlines as $lines){ //add php code here
               echo "<option value='".$lines."'>$lines</option>";
               }?>
            </select>
            
            <input type="text" name="gsm[]" placeholder="GSM" required onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
          
        </div>

    【讨论】:

      【解决方案3】:

      您可以在选择下拉菜单中添加频率图以指示每种类型的出现。您可以使用删除按钮动态添加字段。

      const
        typeSel = document.querySelector('.type-sel'),
        fieldsEl = document.querySelector('.fields');
      
      const main = () => {
        initCounts(typeSel);
      
        document.querySelector('.add-btn').addEventListener('click', handleAdd);
        fieldsEl.addEventListener('click', handleRemove);
      };
      
      const
        setData = (el, key, value) => el.dataset[key] = JSON.stringify(value),
        getData = (el, key) => JSON.parse(el.dataset[key]);
      
      const applyCount = (freq, key, amount = 1) =>
        ({ ...freq, [key]: (freq[key] || 0) + amount });
      
      const frequencyThunk = prop => ({
        init: sel => setData(sel, prop, [...sel.options].reduce((acc, opt) =>  
          ({ ...acc, [opt.value]: 0 }), {})),
        update: (sel, key) => setData(sel, prop, applyCount(getData(sel, prop), key)),
        retrieve: (sel, key) => getData(sel, prop)[key]
      });
      
      const
        selCountFreq = frequencyThunk('counts'),
        initCounts = selCountFreq.init,
        updateCount = selCountFreq.update,
        retrieveCount = selCountFreq.retrieve;
      
      const handleAdd = e => {
        const
          value = typeSel.value,
          index = retrieveCount(typeSel, value),
          fieldEl = document.createElement('div'),
          labelEl = document.createElement('label'),
          inputEl = document.createElement('input'),
          buttonEl = document.createElement('button');
        
        labelEl.textContent = `${value.toUpperCase()}_${index}`;
        fieldEl.classList.add('field');
        Object.assign(fieldEl.dataset, { type: value, index: index });
        buttonEl.textContent = 'Remove';
        buttonEl.dataset.action = 'remove';
        
        fieldEl.append(labelEl);
        fieldEl.append(inputEl);
        fieldEl.append(buttonEl);
        fieldsEl.append(fieldEl);
        
        updateCount(typeSel, value);
      };
      
      const handleRemove = e => {
        if (e.target.dataset.action === 'remove') {
          e.target.closest('.field').remove();
        }
      };
      
      main();
      .controls {
        margin-bottom: 1em;
      }
      
      .fields {
        display: grid;
        grid-auto-flow: row;
        grid-row-gap: 0.5em;
      }
      
      .field {
        display: grid;
        grid-auto-flow: column;
        grid-template-columns: 0.25fr 1fr 0.25fr;
        grid-column-gap: 0.25em;
      }
      
      button[data-action="remove"] {
        cursor: pointer;
      }
      <form onsubmit="return false;">
        <div class="controls">
          <select class="type-sel">
            <option value="a">Input A</option>
            <option value="b">Input B</option>
            <option value="c">Input C</option>
          </select>
          <button class="add-btn">Add</button>
        </div>
        <div class="fields">
          <div class="field">
            <label>Sticky A</label>
            <input value="" />
          </div>
          <div class="field">
            <label>Sticky B</label>
            <input value="" />
          </div>
        </div>
      </form>

      【讨论】:

        【解决方案4】:

        要删除除第一个更改之外的所有项目:

        $('#fieldList').remove();

        $('#fieldList &gt; select:not(:first),input:not(:first)').remove();

        每次从末尾删除一项

         $("#removeMore").click(function(e) {
                  //get select/input elements
                  const elLen = $('#fieldList > select,input');
        
                  //each time you remove a select/input element,
                  //array length decreases and with an if statement you can handle 
                  //which elements to delete 
                  if(elLen.length > 2){
                   $('#fieldList > select:last-child,input:last-child').remove();
                  }
         });
        

        【讨论】:

        • 非常好!但是一个问题。这会同时删除所有的。如果可能的话,我想一次删除一个。所以第一次点击=删除最后添加的。
        • @AndreaSeliz 好的,我会检查它
        • @AndreaSeliz 看看我的回答。可能是您正在寻找的解决方案。
        猜你喜欢
        • 1970-01-01
        • 2013-02-07
        • 2013-04-22
        • 2011-07-15
        • 1970-01-01
        • 2012-02-08
        • 1970-01-01
        • 1970-01-01
        • 2021-12-11
        相关资源
        最近更新 更多