jQuery找到自我

Mot*_*tie 6 jquery jquery-selectors

这可能听起来很奇怪,但我正在研究一个需要在div中找到元素的插件,或者div本身.

脚本根据用户选择查找元素,但内容(包括标记)是可变的.因此脚本将按如下方式查找元素:

$('.block').find(selector); // selector set by user
Run Code Online (Sandbox Code Playgroud)

但是没有一种简单的方法让选择器选择'.block'.在使用find之前选择父级不是解决方案,因为有多个".block"元素.

我知道扩展expr[":"]选择器不会起作用,因为它只是在寻找孩子.但是,我确实通过制作一个':self'选择器找到了一种方法来" 破解 "这种方法:

(function($){
    var orig = $.fn.find;

    $.fn.find = function(sel){
        return (sel === ':self') ? this : orig.call(this,sel);
    }

})(jQuery)
Run Code Online (Sandbox Code Playgroud)

但这似乎有点过头了.而且每次查找函数都会减慢jQuery的处理速度.还有另一种方法吗?


谢谢你的回答!但我最终做到了这一点:

var b = $('.block'),
 el = (b.is(selector)) ? b : b.find(selector);
Run Code Online (Sandbox Code Playgroud)

小智 10

使用find('*')的方法会占用更多的CPU,我建议:

$('.block').find(selector).add($('.block').filter(selector));
Run Code Online (Sandbox Code Playgroud)


Omn*_*ike 8

我也遇到过这个问题.我解决了这个问题(基本上是Romans Malinovskis解决方案作为jquery插件):

$.fn.findAll = function(selector) {
    return this.find(selector).add(this.filter(selector));
};
Run Code Online (Sandbox Code Playgroud)


Evi*_*t7x 6

编辑:

您可以将all选择器'*'与andSelf结合使用,以获得包含其所有子项和子项的元素的选择.然后你可以在所选择的选择器上筛选()选择.

<style type="text/css">li {background-color: white;}</style>
<script type="text/javascript">
$(function () {
  $('div').find('*').andSelf().filter(selector).css('background-color','blue');
}
</script>
<div>
This is a test
  <ul>
    <li class="test">This is a test</li>
    <li>This is a test</li>
    <li class="test">This is a test</li>
    <li>This is a test</li>
    <li class="test">This is a test</li>
    <li>This is a test</li>
  </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

应该更改所有.test对象的背景,以及所选的初始div,如果合适的话.我不确定我的答案的表现.

示例:http://jsfiddle.net/7A9JJ/2/

编辑 或者你可以做$('div,div*').filter(selector);