开发者

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

开发者 https://www.devze.com 2023-02-01 13:55 出处:网络
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.

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 on开发者_Python百科e 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 (i.e. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消