setting default root element in jquery

若如初见. 提交于 2020-01-04 03:57:48

问题


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

Is there any way to change defaults on jQuery like:

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

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

Thanks in advance


Upate

just an update refining the question a bit more here:

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.

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.


回答1:


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

$.defaultRoot.find("div");

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);
}

and then you'd just be able to use

$s("div")

or you could also do a scoped higher order function with something like

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

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

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.




回答2:


$('SELECTOR', 'CONTEXT')

You can use context. As in your case $('div', '.anyOtherRootElement')

For more details, visit http://api.jquery.com/jQuery/




回答3:


Given that you can pass the context as a second argument, you can easily overwrite the $() operator in Javascript with a version which internally calls JQuery using jQuery.noConflict(); and always passes your new root as the second argument.




回答4:


I don't think jQuery provide such method or variable. But you can pass second parameter in jQuery method to set context.

$.defaultRoot = $('.anyOtherRootElement');
$('div', $.defaultRoot ).text("Hello"); // all div inside $('.anyOtherRootElement')
$('div' ).text("Hello"); //all div inside body tag


来源:https://stackoverflow.com/questions/12638781/setting-default-root-element-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!