使用 jQuery 获取类中最近的前一个元素

问题描述 投票:0回答:4
jquery
4个回答
2
投票

prev()
是同级选择器,因此您需要与
input
元素在 dom 中处于同一级别。

您要做的第一件事是使用

closest()
来获取具有类
dropdown-wrapper
的祖先(在这种情况下您也可以使用
parent()
,但如果您更改 dom 结构,最接近的方法更灵活)。根据该结果,您将调用您的
prev

$('.selectable').click(function(){
  $(this).closest('.dropdown-wrapper').prev('.selected').val('hit');
});

0
投票

JS 代码中的倒数第二行应该是:

 $(this).parent().prev('.selected').val('hit');

(你想根据我的理解来解决之前的parent

https://jsfiddle.net/o7s1xgdj/


0
投票

查找元素的一种方法是:

$( ".selectable" ).parent().parent().find('input').val('somevalue');


$( ".selected" ).each(function(index) {
      $(this).on("click", function(){
       This is multiple elements have their own function
       //var somevalue = $(this).attr('id'); 
       });
      });

0
投票

.prev()
只为您提供前一个元素,如果您指定像这样的过滤器选择器
.prev('.selected')
,它仅返回前一个元素(如果它与该选择器匹配)。这意味着如果所需的
.selected
元素不是紧邻当前元素之前,它将不会返回任何内容。

如果你真的想获得类中最接近的前一个元素(即使它不是紧邻当前元素之前),你必须像这样接近它。

currentElem
.prevAll('.selected') // returns all previous elems with 'selected' class in reverse DOM order (the closest is the first)
.eq(0); // return the first element in the set - the closest one

因此在你的情况下

$('.selectable').click(function(){
  $(this).closest('.dropdown-wrapper').prevAll('.selected').eq(0).val('hit');
});
© www.soinside.com 2019 - 2024. All rights reserved.