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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:09:44  来源:igfitidea点击:

jQuery: Find previous element with class

javascriptjquery

提问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/

小提琴:http: //jsfiddle.net/Mcujp/4/

回答by George Cummins

If you are trying to get the preceding sibling, use .prev().

如果您尝试获取前面的兄弟,请使用.prev().

If you are trying to get the sibling of the parent (like in your example) use .parent().prev().

如果您试图获取父级的兄弟姐妹(如您的示例),请使用.parent().prev().

回答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 :)

希望我的定义很简单:)