JS 代码中的倒数第二行应该是:
$(this).parent().prev('.selected').val('hit');
(你想根据我的理解来解决之前的parent)
查找元素的一种方法是:
$( ".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');
});
});
.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');
});