[英]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.
我可以随时使用我的JQUERY选择器...但是我没有检查选择器是否存在,而是使用.each函数。
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). 我知道这看起来有点多,尤其是如果您只需要一个选择器时,但我想不出更好的方法(除了在每个选择器处使用if脚的if语句)。 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.
注意,#mySelector(因为它是一个ID)仅被允许一次。
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: 如果我真的想避免只使用普通的
if
语句,那么我可能只想使用一个简单的函数,例如:
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). 您真正需要做的就是检查您所做的每个选择的
length
属性(即list
, tag
, float
变量)。
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:
正如Donald Knuth所说:
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
我们应该忘记效率低下的问题,例如大约97%的时间:过早的优化是万恶之源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.