jQuery:使用类查找上一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16451214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: Find previous element with class
提问by Peter Lur
I have a really simple problem.
我有一个非常简单的问题。
How can I find the first previous element of another element? I tried the code below without success.
如何找到另一个元素的第一个前一个元素?我尝试了下面的代码但没有成功。
HTML:
HTML:
<div class = "A">HERE</div>
<div class="B">
<div class="C" style="width:50px;height:50px;background-color:#000000;"></div>
</div>
JS:
JS:
$('.C').click(function() {
alert($(this).closest('.A').html());
});
Fiddle: http://jsfiddle.net/Mcujp/4/
回答by George Cummins
回答by cortex
Try this:
尝试这个:
$('.C').click(function() {
alert($(this).parent().prev('.A').html());
});
回答by hnafar
$('.C').click(function() {
alert($(this).closest('.B').prev('.A').html());
});
回答by shah Safiullah Jan
if you want to target closest children of top parent you can do so as something define below.
如果您想针对顶级父母的最近孩子,您可以按照以下定义进行操作。
lets assume you have an HTML like
让我们假设你有一个像
<div class="top-parent">
<div class="parent">
<button class="add-button">Child of 1st Parent DIV</button>
</div>
<div class="parent">
<button class="add-button">Child of 2nd Parent DIV</button>
</div>
</div>
<script>
$(document).on('click','.add-button',function(){
$(this).parents('.parent').prev().closest('.parent').find('.add-button').text('im clicked by one of the button next to my parent')
$(this).parents('.parent').remove();
})
</script>
similarly if you want to target grandparent next parent containers children just change .prev()
to .next()
同样,如果您想针对祖父母下一个父容器,孩子只需更改.prev()
为.next()
hope i made it simple to define :)
希望我的定义很简单:)