是否有可能以某种方式重新配置 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#divTwo
而 div#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() 等...
。
您可以使用 closest 来传递上下文:
var namespace = $(".my-namespace").get()[0];
$(".foo").closest("p.bar", namespace);
关于javascript - 强制 jQuery 只在指定元素的子树中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21927484/