1

当我使用 $("child").remove() 或 $("child").empty() 时,它会从页面中删除所有子元素,我希望它只从一个父元素中删除子元素。这个页面上有更多的父类,所以无论如何我可以在用户单击按钮类时仅从父类中删除内容.. button_parent 类与父类处于同一级别

<div class ="button_parent"><div class ="button"></div></div>
    <div class = "parent">

        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div> 
    </div>
<div class ="button_parent"><div class ="button"></div></div>
    <div class = "parent">
        <div class ="button"></div>
        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div> 
    </div>
<div class ="button_parent"><div class ="button"></div></div>
    <div class = "parent">
        <div class ="button"></div>
        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div> 
    </div>
<div class ="button_parent"><div class ="button"></div></div>    
    <div class = "parent">
        <div class ="button"></div>
        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div> 
    </div>
<div class ="button_parent"><div class ="button"></div></div>
    <div class = "parent">
        <div class ="button"></div>
        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div> 
    </div>
<div class ="button_parent"><div class ="button"></div></div>    
    <div class = "parent">
        <div class ="button"></div>
        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div>
        <div class= "child"></div> 
    </div>
4

2 回答 2

3

.remove()删除元素,但.empty只删除内容。无论如何..您需要使用as 上下文删除childdivparent

$('.parent').click(function () {
   $(this).find('.child').remove();
});

对于 HTML:

<div class ="button_parent"><div class ="button"></div></div>
<div class = "parent">

    <div class= "child"></div>
    <div class= "child"></div>
    <div class= "child"></div>
    <div class= "child"></div> 
</div>

你可以做

$('.button').click(function() {
    $(this).parent() //this will be .button_parent
           .next()   //next node is .parent
           .find('child')  //find all child in .parent 
           .remove()       //remove them
});

您可以使用.empty().childdiv 是内部唯一存在的 div.parent

于 2012-10-31T19:01:41.470 回答
-1

在这种情况下,最好使用 id 而不是 css 选择器

为要维护此操作的 div 提供明确的 id。您可以保持您的类完好无损,并且仅将 id 应用于您希望操作发生的 div

<div class = "parent" id="operation">
    <div class= "child"></div>
    <div class= "child"></div>
    <div class= "child"></div>
    <div class= "child"></div> 
</div>
于 2012-10-31T19:03:21.070 回答