【问题标题】:How to access appended element and remove it?如何访问附加元素并将其删除?
【发布时间】:2015-02-19 21:48:06
【问题描述】:

我对此进行了大量研究,但无法完全理解它。

有一个父 div .container。其中有许多子div,里面有不同的文本。 .container 外面有两个按钮。一种用于动态创建和附加具有特定文本的子元素。其他是删除具有特定文本的子 div。

第一次加载页面时一切正常,但是当添加一个新的子 div 时(假设有文本 xyz)然后使用在 textarea 中输入 xyz 并按下删除按钮(编码用于删除具有文本 xyz 的子 div他们)它不起作用。 示例 HTML 标记(可能有无限数量的子 div)

  <div class="container>
  <div class="child1"></div>
  <div class="child2"></div>
  <div class="child3"></div>
  <div class="child4"></div>
  </div>
  <button class="AppendWithSomeText"></button>
  <button class="RemoveDivWithSomeMatchedText"></button>
  <textarea></textarea>

用于添加 div 的 jquery

     var newdiv = = document.createElement('div');
     newdiv.className = 'child';
     $(".container").append(newdiv);
     $(".container").find(".child").html(textfromtextarea);
     // here text from text area is a string stored from user input in             textarea

删除按钮的jQuery

    $('.container>div:contains("'+textfromtextarea+'")').remove();
    //works only first time

【问题讨论】:

  • 请张贴小提琴。
  • 你能发布你的jquery来添加div吗?

标签: javascript jquery html css


【解决方案1】:

http://codepen.io/dustinpoissant/pen/VYXGwB

HTML

<input type='text' id='input' />
<button onclick='addItem()'>Add</button>
<button onclick='removeItem()'>Remove</button>
<br><br>
<div id='box'></div>

JavaScript

function addItem(){
  $("#box").append("<span>"+$("#input").val();+"</span>");
}
function removeItem(){
  var text = $("#input").val();
  $("#box span").each(function(i, el){
    if($(el).text()==text) $(el).remove();
  });
}

【讨论】:

    【解决方案2】:

    为了保持结构的统一性,我添加了 child-number 类型的类。

    我希望这是你所期望的。

    $(document).ready(function() {
      $(".AppendWithSomeText").on("click", function() {
    
        $(".container").append("<div class=child" + ($("[class^='child']").length + 1) + ">" + $(".content").val() + "</div>")
      })
      $(".RemoveDivWithSomeMatchedText").on("click", function() {
    
        $('.container>div:contains("' + $(".content").val() + '")').remove();
      })
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="container">
      <div class="child1">somecontent</div>
      <div class="child2">somecontent</div>
      <div class="child3">somecontent</div>
      <div class="child4">somecontent</div>
    </div>
    <button class="AppendWithSomeText">add</button>
    <button class="RemoveDivWithSomeMatchedText">remove</button>
    <textarea class="content"></textarea>

    【讨论】:

      猜你喜欢
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      相关资源
      最近更新 更多