jQuery - 搜索相对于当前选择器的上一个选择器

标签 jquery jquery-selectors

我有一个包含 3 个部分的表单。每个部分都有一个专用的 div,用于显示有关具有焦点的输入的相当长的上下文帮助消息。

我的问题是,如果我给每个帮助 div 一个“form-tip”类,并且每个有提示的输入为“has-tip”类,我怎样才能让提示始终显示在之前的“form-tip”div?

类似于:

$('.has-tip').each(focus(function() {
    var tip = $(this).attr('title');
    // Find most recent $('.form-tip') in the DOM and populate it with tip
}));

我希望这是有道理的...感谢您的帮助。

最佳答案

如果 .has-tip.form-tip 的子项,那么您可以使用 .closest()像这样:

$('.has-tip').each(focus(function() {
    var tip = $(this).attr('title');
    var ft = $(this).closest('.form-tip');
    // Find most recent $('.form-tip') in the DOM and populate it with tip
}));

如果是同级,可以使用.prev('.form-tip')或者如果它不是立即之前,那么它是 .prevAll('.form-tip: first') .

关于jQuery - 搜索相对于当前选择器的上一个选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3034370/

相关文章:

jquery - 使用 switchClass 悬停在父类上的子类,但不影响具有相同类的其他 div

jquery - 在jQuery中选择两个具有相同id的不同HTML元素类型

javascript - 每 10 秒使用 querySelector 更改背景图像不起作用

javascript - JavaScript 中的选择器

javascript - 动态 id 选择器未被调用或实例化

javascript - jQuery 选择器中的波浪号

javascript - 选择下拉菜单时重定向到不同的 View ,然后单击按钮

javascript - 如何在日期范围选择器中使用 isInvalidDate 禁用多个日期

javascript - 使用 Hammer.js 拖动事件

javascript - 在日期选择器中选择后禁用日期