javascript - 强制 jQuery 只在指定元素的子树中搜索

标签 javascript jquery

是否有可能以某种方式重新配置 jQuery 以仅在指定元素的子树中搜索?

我需要做这样的事情:

var lockToSubtree = function (jq) {
        //reconfigure jq
        return reconfiguredJQuery;
    },

    myJQuery = lockToSubtree(jQuery, '.my-namespace');

所以我有自己的 jQuery 实例,它只在“.my-namespace”中搜索元素。

为了说明我的需求,这里有一个示例 HTML:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
    <div id="divOne" class="someClass"></div>
    <div class="my-namespace">
        <div id="divTwo" class="someClass"></div>
    </div>
</body>
</html>

所以我以后可以在我的代码中使用:

var $el = myJQuery('.someClass');

它只会在 .my-namespace 的子树中搜索 .someClass。所以它将只返回 div#divTwodiv#divOne 将被跳过,因为它不在 .my-namespace 的子树下。

重点是,当使用 .closest()< 等 jQuery 函数时,我需要它继续在 .my-namespace 的子树中搜索等,看最后的代码片段:

var $myJQuery = lockToSubtree(jQuery, '.my-namespace'),
    $el = myJQuery('.someClass'); // $el is the #divTwo element

$el.closest('body'); // finds nothing, because body is not located under .my-namespace

更新:

我同意@Keith 的观点,即重新配置 jQuery 以在某些子树中搜索也可能无法使用向上搜索的 .closest 方法。因此,只有当搜索方向向下时,我才可以在子树中搜索。

我想强调的是,我需要 jQuery 函数具有与原始 jQuery 相同的功能(如 jQuery.fn 等属性)。

The real life scenario: I need to scope some third party library in our project so it would not affect HTML until some level of depth. The library is a one line of a JavaScript minified code using global jQuery object. All I need is to wrap it in self-invoking function and pass to it some modification of jQuery function which searches only in some subtree of a DOM, but contains all the properties as normal jQuery.

这段代码也许能更好地解释它:

(function (jQuery) {
    // I am passing jQuery through parameter
    // ... here is the library code
}(/* here I want to inject modified jQuery */));

最佳答案

您可以像这样为 jQuery 选择器创建一个包装器函数:

$Q = function (select, opts) {
    return $(".my-namespace", opts).find(select);
};

然后像调用 jQuery 一样调用包装器 $Q(".element").children() 等...

jSFiddle here

您可以使用 closest 来传递上下文:

var namespace = $(".my-namespace").get()[0];

$(".foo").closest("p.bar", namespace);

关于javascript - 强制 jQuery 只在指定元素的子树中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21927484/

相关文章:

javascript - 来自 elasticsearch 的 406( Not Acceptable )错误代码是什么意思?

javascript - 项目配置中的 EXTJS 内联 initComponent 方法

javascript - FlowType 中可能有不兼容的别名?

javascript - 带有外部参数 Angular 的 Ajax

javascript - eval 在执行具有 return 语句的函数时总是返回错误

javascript - 如何使用 jQuery 预格式化电话号码字段?

javascript - 联系页面设计如何添加Bootstrap

jquery - 如何在 jQuery AJAX 调用期间阻止将当前域添加到 URL 前面

javascript - 将图像 + 数据 ajax post 发送到 ashx 处理程序

javascript - .vue 组件中的条件样式表