需要帮助来确定为什么在jQuery中删除元素及其内容不起作用
谁能告诉我这个jQuery代码在这里做错了什么?
$('.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; }
xwww.firsturl.com
xwww.anothereurl.com
xwww.athirdurl.com
它可以正常删除.deleter
元素:
https://jsfiddle.net/Hastig/ku0t7mey/5/
但是一旦$('.urls').text($('.urls').text().replace(toDelete, ''));
在元素.deleter被删除但内容(x)被留下:
https://jsfiddle.net/Hastig/ku0t7mey/4/
UPDATE
我可以在这里使用此解决方案获得整个function。
但是我会把这个问题留给任何能够回答为什么我使用的代码似乎删除了目标元素中的所有html元素的人。
https://jsfiddle.net/Hastig/ku0t7mey/6/
您可以使用.nextSibling
, .textContent
将与单击的.deleter
元素相邻的#text
节点设置为空字符串""
。
$('.deleter').click(function(e) { var toDelete = $(this).data('stringStorage'); this.nextSibling.textContent = ""; $(this).remove(); });
您还可以在html
使用data-*
属性替换自定义属性
xwww.firsturl.com
xwww.anothereurl.com
xwww.athirdurl.com
jsfiddle https://jsfiddle.net/ku0t7mey/8/
您也可以使用.contents()
.filter()
.trim()
.add()
删除同一个调用中的#text
节点,该节点从document
删除
$(".urls").contents().filter(function() { return this.nodeType === 3 && this.nodeValue.trim() === toDelete }).add(this).remove();
检查一下: https : //jsfiddle.net/ku0t7mey/7/
像以下一样修改HTML:
xwww.firsturl.com xwww.anothereurl.com xwww.athirdurl.comsss
JS喜欢:
$('.deleter').click(function() { var toDelete = $(this).attr('stringStorage'); $(this).parent().remove(); });
试试这个jsfiddle
HTML
xwww.firsturl.com
xwww.anothereurl.com
xwww.athirdurl.com
脚本
$('.delete').click(function() { var toDelete = $(this).attr('stringStorage'); $(this).remove(); });