在jquery中设置默认根元素 [英] setting default root element in jquery

查看:105
本文介绍了在jquery中设置默认根元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery目前使用窗口作为其默认元素,因此任何类似 $('div')的调用都将查找 div 窗口内的标签

jQuery currently uses window as its default element so any call like $('div') will look for div tags inside window.

有什么办法吗?更改jQuery的默认值,如:

Is there any way to change defaults on jQuery like:

$.defaultRoot = $('.anyOtherRootElement');
$('div').text("Hello");

这将选择包含 .anyOtherRootElement class。

this will select any div inside the elements containing .anyOtherRootElement class.

提前致谢

这里只是一个更新问题的更新:

just an update refining the question a bit more here:

我想执行上面的操作来自外部脚本的外部查询,它不知道 defaultRoot 是什么,所以他们仍然可以调用应该是当前基数,所以在这个例子中,我'不幸的是,恐怕不会添加第二个参数。

I would like to perform the actions above based on external queries coming from external script which won't know what defaultRoot is so they can still be calling what is supposed to be the current base, so in this instance, I'm afraid adding the a second parameter wouldn't be an option, unfortunately.

同时创建一个函数返回 defaultRoot.find(el)会阻止我使用第一级方法,如 $ .trim $。每个等......所以不幸的是,这也是不可能的。

And at the same time creating a function which returns defaultRoot.find(el) would prevent me of using first-level methods such $.trim, $.each, etc… so unfortunately that would not be possible as well.

推荐答案

理想情况(出于性能原因)您想要使用 find()

Ideally (for performance reasons) you'd want to use find()

$.defaultRoot.find("div");

否则你可以使用设置上下文的2参数形式

Otherwise you can use the 2 argument form that sets a context

   $("div", $.defaultRoot);

一般来说,你不想隐含地做这些类型的事情,因为其他人很容易就会结束在以后必须使用您的代码时彻底混淆。如果你想要一贯地做它并缩短它,你应该创建自己的函数,如:

In general you don't want to do these types of things implicitly since someone else could easily end up thoroughly confused when having to work with your code later. If you want to do it consistently and make it shorter you should create your own function to do so like:

var $s = function(selector) {
  return $.defaultRoot.find(selector);
}

然后你就可以使用

$s("div")

或者您也可以使用类似

var withScope = function(scope$) {
  return function(selector) {
    return scope$.find(selector);
  }
}

var $s = withScope($.defaultRoot);
$s("div")

如果由于某种原因你真的想要搞砸对于客户端代码的默认状态(请求混乱IMO),你应该看看功能实践:currying。

If for some reason you really want to screw around with the default state for client code (begging for chaos IMO), you should look at the functional practice: currying.

这篇关于在jquery中设置默认根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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