jQuery 获取元素下方

标签 jquery

我需要检索位于 DOM 下面的特定类的元素。例如:

<div>
    <a onclick="someMethod(this)">
</div>
<div class="specificClass">
</div>

在 someMethod 中,我有 anchor ,但需要检索位于下面的类“specicClass”的第一个元素。

更新。 <div class="specificClass"> 的位置没有指定。我唯一知道的 - 它位于下面

最佳答案

演示: http://jsfiddle.net/reKwQ/1/

不要使用 onclick 属性,而是为您的 anchor 指定一个类或 ID:

<div>
    <a class="someClass">
</div>
<div class="specificClass"></div>

然后使用 jQuery 将单击事件绑定(bind)到它并从那里开始:

$('a.someClass').click(function() {
    var $elements = $('a.someClass, .specificClass');

    var foundThis = false,
        $nextSpecificClass = null,
        $this = $(this);

    $elements.each(function() {
        var $element = $(this);
        if (foundThis === false && $element[0] == $this[0]) {
            foundThis = true;
        } else if (foundThis === true && $element.is('.specificClass')) {
            $nextSpecificClass = $element;
            return false;
        }
    });

    // Do something  with $nextSpecificClass here

    return false;
});

这是有效的,因为您有一个包含 anchor 和目标元素的匹配元素列表,这些元素将按发现的顺序排列。

一旦找到我们点击的内容,我们就可以接受下一个可用的 .specicClass 元素作为我们的结果。

演示: http://jsfiddle.net/reKwQ/1/

关于jQuery 获取元素下方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4628533/

相关文章:

jquery - Knockoutjs 绑定(bind)鼠标悬停或 Jquery

javascript - 我的 JQuery 数据表有错误。 JQuery Datatable 在本地环境中工作正常,但在托管环境中却出现错误

jquery - Ajax 调用提交处理程序 Jquery 验证

javascript - 使用 angularJS 和 jquery 的最佳方法 $ ('document' ).ready()

javascript - 使用 jquery 从输入中获取文件名列表

javascript - 无法在 PHP echo 中调用 jQuery

jquery - 通过单击添加类时淡入 1000

jQuery mobile,多个页面的 pageshow 事件

javascript - 数据表搜索单击的元素

jquery - 使用 JQuery 和 Rails 生成链接预览