jquery - 如何使用 Jquery 向后遍历一条链?

标签 jquery

我认为 jquery 中有一些东西可以让你通过一条链向后移动。

我想这样做:

var a = $(this).parent().addClass('test').goBackToParent().children('selectorHere').text()

我想获取我拥有的对象的父对象并向其添加一个类名。一旦我这样做了,我想遍历它的子级并找到一个与我的选择器匹配的子级并获取其文本。

我可以这样做吗,还是我必须这样做:

$(this).parent().addClass('test');
var a = $(this).parent().children('selectorHere').text()

编辑

我现在使用“end”,但它不起作用我做了一个例子,你可以尝试 here

<table>
    <th>
        <tr>one</tr>
        <tr>two</tr>
    </th>
    <tr>
        <td id="test"><a href="#"><img src="http://ais.web.cern.ch/ais/apps/hrt/SMT%20v2/Images/btnbar_edit.png" /></a></td>
        <td class="selectMe">1</td>
    </tr>
</table>

$(function() {
    $('#test').click(function() {
        // does not work
        var a = $(this).parent().addClass('afb')
                   .end().children('.selectMe').text();

        // works
        var b = $(this).parent().children('.selectMe').text();

        alert(a + ' -should have value');
        alert(b + ' -works');

        return false;
    });
});

最佳答案

您正在寻找end()方法:

var a = $(this).parent().addClass('test').end()
               .children('selectorHere').text();

方法:

Ends the most recent filtering operation in the current chain and returns the set of matched elements to its previous state.

更新:根据您的html片段,您实际上根本不需要end!关于 jQuery 的重要一点是,大多数非遍历方法都会返回自身的副本 - 因此,如果您调用 $(this).addClass('test'),您将获得 $(this) 的副本。

所以对于你的代码片段:

// does not work
var a = $(this)                       // points at #test
           .parent()                  // now refers to the tr which holds test
               .addClass('afb')       // still refers to the tr
               .end()                 // now we're back to #test
           .children('.selectMe')     // empty! there are no direct children of #test which match .selectMe
               .text();               // empty

相反,尝试一下没有结束:

// works
var a = $(this)                       // points at #test
           .parent()                  // now refers to the tr which holds test
               .addClass('afb')       // still refers to the tr
           .children('.selectMe')     // found the .selectMe td
               .text();               // returns '1'

关于jquery - 如何使用 Jquery 向后遍历一条链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5317419/

相关文章:

javascript - 如何在 window.scrollTo(x-coord, y-coord); 中控制滚动速度;

javascript - 自动将用户重定向到上一页

javascript - jQuery:如何在尚未添加到 DOM 的元素上调用 jQuery 插件函数?

javascript - 如何使文本框增长到其父div的宽度

javascript - 了解插件代码中 $.each 内部传递的参数的用法

javascript - 流畅更换背景图片

java - 如何对导航和内容之间的交互进行编程

jQuery 从服务器获取图像并显示为弹出窗口

jQuery 插件使文本适合宽度/高度定义的元素

jquery - 如何使 Bootstrap 不覆盖我的特定样式?