<div class="parent">
<span>sometext</span>
plain text
<input class="child">
</div>
<div class="parent">
<span>sometext</span>
plain text
<input class="child">
</div>
<div class="parent">
<span>sometext</span>
plain text
<input class="child">
</div>
如何安全地删除.parent
中除.child
之外的所有内容?
我使用的是这个代码(其中items
是.child
的堆栈,each
是.child
(
items.each(function(){
$(this).parent().children().each(function(){
if ($(this).hasClass('child'))
// do something
else
$(this).remove();
});
$(this).unwrap(); // remove parent, keep only .child
});
但它不能处理纯文本。
你说过
.parent
中可以有多个.child
,我们只保留第一个。所以如果有三个,第二个和第三个应该去掉。
以及
items
是.child
的堆栈,每个是.child
好吧,那么这就是我要做的:
items.parent('.parent').each(function() {
var parent = $(this),
child = parent.children('.child').first();
child.detach();
parent.empty().append(child);
});
它的作用:
从
.child
元素的集合上移到.parent
元素的集合。生成的集合将仅具有唯一的父对象。在父母之间循环。
获取每个父级中的第一个
.child
并将其分离。清空
.parent
。重新连接
.child
。
最终结果是,每个.parent
将只有一个.child
(并且没有其他子级,无论是否为.child
(。
这里有一个纯JS的解决方案:fiddle
因此,在您的循环中,您可以使用以下内容:
this.parentNode.innerHTML = this.outerHTML;
如果您必须保留附加的事件处理程序:
var _this = this.cloneNode(true),
parent = this.parentNode;
parent.innerHTML = '';
parent.appendChild(_this);
这样的东西就可以了;
$('.parent').on('click', '.child', function(e) {
var $this = $(this),
$parent = $this.parent(),
$children = $parent.find('.child'); // or: $this.siblings('.child');
$parent
.empty() // Empty the "parent" element
.append($children); // Re-append all "child" element to "parent"
$this.focus(); // Focus the (input) element
});
这里有一个使用正则表达式的替代方案:
$('.parent').each(function() {
$(this).html($(this).html().match("<input class=.child.>"));
});