我为此做了很多研究,但无法理解它。
有一个父 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
最佳答案
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();
});
}
关于javascript - 如何访问附加元素并将其删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28617591/