需要帮助来确定为什么在jQuery中删除元素及其内容不起作用 [英] Need help to identify why removing element and its contents in jQuery is not working
问题描述
有人能告诉我这个jQuery代码我做错了吗?
Can anybody tell me what I'm doing wrong with this jQuery code here?
$('.deleter').click(function() {
var toDelete = $(this).attr('stringStorage');
$('.urls').text($('.urls').text().replace(toDelete, ''));
$(this).remove();
});
.deleter {
display: inline-block;
margin-right: 10px;
background-color: red;
color: white;
cursor: pointer;
}
.deleter:hover { background-color: orange; }
br { line-height: 22px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="urls">
<span class="deleter" stringStorage="www.firsturl.com">x</span>www.firsturl.com<br>
<span class="deleter" stringStorage="www.anothereurl.com">x</span>www.anothereurl.com<br>
<span class="deleter" stringStorage="www.athirdurl.com">x</span>www.athirdurl.com<br>
</div>
它可以正常删除 .deleter
元素:
https://jsfiddle.net/Hastig/ku0t7mey / 5 /
但是一旦 $('。urls')。text($('。urls')。text( ).replace(toDelete,''));元素.deleter中的
被删除但内容(x)被遗忘:
But once $('.urls').text($('.urls').text().replace(toDelete, ''));
in the element .deleter is removed but the contents (x) are left behind:
https://jsfiddle.net/Hastig/ku0t7mey/4/
UPDATE
我可以使用这里有这个解决方案。
但是我会把这个问题留给任何能够回答代码原因的人我用过似乎删除所有html元素withi n目标元素。
But I will leave this question open for anyone who can answer why the code I used seems to remove all html elements within the targeted element.
https:/ /jsfiddle.net/Hastig/ku0t7mey/6/
推荐答案
您可以使用。 nextSibling
, .textContent
设置 #text
与点击的 .deleter
要清空字符串的元素。
You can use .nextSibling
, .textContent
to set #text
node adjacent to clicked .deleter
element to empty string ""
.
$('.deleter').click(function(e) {
var toDelete = $(this).data('stringStorage');
this.nextSibling.textContent = "";
$(this).remove();
});
您也可以使用替换数据 - *
自定义属性的属性 html
You can also substitute using data-*
attribute for custom attribute at html
<div class="urls">
<span class="deleter" data-string-storage="www.firsturl.com">x</span>www.firsturl.com<br>
<span class="deleter" data-string-storage="www.anothereurl.com">x</span>www.anothereurl.com<br>
<span class="deleter" data-string-storage="www.athirdurl.com">x</span>www.athirdurl.com<br>
</div>
jsfiddle https://jsfiddle.net/ku0t7mey/8/
jsfiddle https://jsfiddle.net/ku0t7mey/8/
您也可以使用 .contents()
, .filter()
, .trim()
,。 add()
在相同的调用中删除 #text
节点,其中此
已从 document
you could alternatively use .contents()
, .filter()
, .trim()
, .add()
to remove the #text
node at same call where this
is removed from document
$(".urls").contents().filter(function() {
return this.nodeType === 3 && this.nodeValue.trim() === toDelete
}).add(this).remove();
https://jsfiddle.net/ku0t7mey/12/
这篇关于需要帮助来确定为什么在jQuery中删除元素及其内容不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!