简体   繁体   中英

My JQuery exist function: does it make sense or not?

I'm a bit confused the last couple a days. I use my JQUERY selectors whenever I like... but I didn't check whether a selector exist or not, instead I used the .each function.

  var exist = function(obj){
    var returnObject ={};
    for(var key in obj){
      if(obj[key].length){
        returnObject[key] = obj[key];
      }else {
        return false;
      }
    }
    return returnObject;
  }
  //define all your selectors that would be needed for core functionality.
  var activeSelectors = exist({
    selList : $('div.selectorone'),
    selTag : $('a#tagtwo'),
    selFloat : $(div.float) /*etc etc*/

  }) 

  if (activeSelectors) {
    console.log('all my core selectors are here!');
     /* do Stuff*/
  }

I know this looks a bit much, especially if you need only one selector, but I can't figure out a better way (except a lame if statement at every selector). I saw people using

$('div#mySelector').each(function(){ /* do stuff*/});

but I don't agree that it's nice. Notice that #mySelector (because it's an id) is only once allowed.

I would love the feedback. Please consider the performance vs Nice programming.

for more info please comment below or contact me!

If I really wanted to avoid just using a plain if statement, then I'd probably just go with a simple function like this:

var exists = function()
{
    for (var i in arguments)
    {
        if ($(arguments[i]).length == 0)
        {
            return false;
        }
    }

    return true;
}

And invoke it like this:

var list = $('div.selectorone');
var tag = $('a#tagtwo');
var float = $('div.float');
if (exists(list, tag, float))
{
    // Do some stuff.
}

Or:

if (exists('div.selectorone', 'a#tagtwo', 'div.float'))
{
    // Do some stuff.
}

I do think you're over-engineering the problem though. All you really need to do is check the length property on each of the selections you've made (ie the list , tag , float variables).

Also, performance is a complete non-issue here; is the method of checking whether the elements exist actually going to affect the user experience for your site? As Donald Knuth said:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM