nic*_*ckf 10 javascript jquery
使用jQuery,如何匹配DOM树中当前元素之前的元素?使用prevAll()只匹配以前的兄弟姐妹.
例如:
<table>
<tr>
<td class="findme">find this one</td>
</tr>
<tr>
<td><a href="#" class="myLinks">find the previous .findme</a></td>
</tr>
<tr>
<td class="findme">don't find this one</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
在我的具体情况下,我将在点击链接之前搜索第一个 .findme元素.
nic*_*ckf 21
好的,这就是我想出来的 - 希望它在许多不同的情况下都会有用.这是2个扩展到jQuery的,我叫prevALL和nextALL.虽然标准prevAll()与之前的兄弟姐妹prevALL()匹配,但在DOM树中一直匹配所有以前的元素,类似于nextAll()和nextALL().
我将在下面的评论中尝试解释它:
// this is a small helper extension i stole from
// http://www.texotela.co.uk/code/jquery/reverse/
// it merely reverses the order of a jQuery set.
$.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
// create two new functions: prevALL and nextALL. they're very similar, hence this style.
$.each( ['prev', 'next'], function(unusedIndex, name) {
$.fn[ name + 'ALL' ] = function(matchExpr) {
// get all the elements in the body, including the body.
var $all = $('body').find('*').andSelf();
// slice the $all object according to which way we're looking
$all = (name == 'prev')
? $all.slice(0, $all.index(this)).reverse()
: $all.slice($all.index(this) + 1)
;
// filter the matches if specified
if (matchExpr) $all = $all.filter(matchExpr);
return $all;
};
});
Run Code Online (Sandbox Code Playgroud)
用法:
$('.myLinks').click(function() {
$(this)
.prevALL('.findme:first')
.html("You found me!")
;
// set previous nodes to blue
$(this).prevALL().css('backgroundColor', 'blue');
// set following nodes to red
$(this).nextALL().css('backgroundColor', 'red');
});
Run Code Online (Sandbox Code Playgroud)
编辑 - 从头开始重写的功能.我只是想到了一种更快捷,更简单的方法.查看编辑历史记录以查看我的第一次迭代.
再次编辑 - 找到了一种更简单的方法!