我认为 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/