jQuery找到自我 [英] jQuery find self

查看:68
本文介绍了jQuery找到自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来可能很奇怪,但是我正在开发一个需要在div或div本身中查找元素的插件.

This may sound odd, but I'm working on a plugin that needs to find elements within a div, or the div itself.

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

The script finds an element based on a user selection, but the contents, including the markup is variable. So the script will look for the element as follows:

$('.block').find(selector); // selector set by user

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

but there isn't an easy way to have the selector select the '.block'. Selecting the parent before using find isn't a solution, as there are multiple '.block' elements.

我知道扩展expr[":"]选择器是行不通的,因为它只是在寻找孩子.但是,我确实找到了一种方法"鸭子打孔" ,通过创建:self"选择器:

I know extending the expr[":"] selector won't work as it is only looking for children. But, I did figure out a way to "duck punch" this method, by making a ':self' selector:

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

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

})(jQuery)

但这似乎有点过头了.而且,这会使jQuery的每个find函数的处理速度变慢.还有另一种方法吗?

But this seems a bit over the top. And it will slow jQuery processing a tiny bit with every find function. Is there another way to do this?

感谢您的回答!但是我最终还是这样做了:

Thanks for the answers! But I ended up doing this:

var b = $('.block'),
 el = (b.is(selector)) ? b : b.find(selector);

推荐答案

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

approach with find('*') would be much more CPU intensive and I would recommend:

$('.block').find(selector).add($('.block').filter(selector));

这篇关于jQuery找到自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆