2012-10-31 35 views
1

我一直在寻找这样的问题,但我无法找到它。隐藏一个div,但不指定id或类

我有结构,看起来像这样:

<div id="[email protected](item.ProductId)" class="productholder"> 
    <img src="@Html.DisplayFor(modelItem => item.Image)" alt="" /> 
    <div class="productinfo"> 
    <h2>@Html.DisplayFor(modelItem => item.Name)</h2> 
    <p>@Html.DisplayFor(modelItem=> item.Description)</p> 
    <br /> 
    </div> 
    <div class="productprice">  
    <h2>@Html.DisplayFor(modelItem => item.price):-</h2>   
    <input type="button" value="Ta bort" class="b" data-ProductImageId='@item.ProductImageId'>       
    </div>         
</div> 

我想要做的是,当有人点击有class="b"整个div标签应该得到隐藏的.hide()问题的按钮是,我有这些div标签中的10个看起来相同,所以我不能指定div标签,因为它的重要性在于我单击的按钮内部的div标签被隐藏。

我想我需要使用父母或类似的东西?

我曾尝试以下的jQuery脚本:

<script type="text/javascript"> 
    $(document).ready(function() { 
     $(".b").click(function() { 
      $("div:eq(0)").hide(); 
     }); 
    }); 
</script> 

但我弄清楚它不会工作怎么一回事,因为它会隐藏整个DIV包装。

任何类型的解决方案,表示赞赏!

回答

1
$(".b").click(function() { 
     $(this).parent().hide(); 
    }); 

$(".b").click(function() { 
     $(this).parent().parent().hide(); 
    }); 
+0

第二次工作完美! – Obsivus

+0

很酷,你能否将答案标记为正确? –

0

你很接近,只是隐藏按钮的父:

$(".b").click(function() { 
     $(this).parent('div').hide(); 
    }); 

或者,如果你想确保即使更改了层次一点点的div获得隐藏:

$(".b").click(function() { 
     $(this).parents('div.productprice').hide(); 
    }); 
0

基本的DOM:每个DOM节点都有一个父元素:

$('.b').click(function() { 
    $(this).parent('div.productprice').hide(); 
}); 
1

我想你试图隐藏整个容器..尝试使用closest

$(this).closest('.productholder').hide() 

或者如果你只是想隐藏父格,然后只需使用.parent()

$(this).parent().hide() 

全码:

$(document).ready(function() { 
    $(".b").click(function() { 
     $(this).closest('.productholder').hide(); 
     // or $(this).parent().hide() 
    }); 
});