当找不到jQuery选择器时会发生什么? [英] What happens when a jQuery selector wasn't found?

查看:136
本文介绍了当找不到jQuery选择器时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将一个selector作为parameter传递给函数.

If I pass one selector as a parameter to a function.

// selector is an object
function(selector) {

  selector.trigger('eventHere');
}

很明显,如果传入的selector没有此event,则event将永远不会触发,但是在触发事件之前我应该​​做一些条件检查吗?我的意思是:

Obviously, the event will never fire if the selector that was passed in didn't have this event, but should I do some condition checking before triggering the event? I mean:

// selector is an object
if(selector === 'matched'){
  // then fire the event
}
else{
  // do nothing
}

还是就让它...?

推荐答案

关于jQuery的好处是,如果选择器不匹配,它将不会引发异常或导致错误.因此,您无需执行任何其他操作.这是一个安全的操作:

The nice thing about jQuery is that it will not throw an exception or cause an error if the selector doesn't match. So you needn't do anything extra; this is a safe operation:

// selector **must** be a jQuery object
// the assumption here is that you've already done 
// var selector = $('selectorString'); elsewhere
// and have invoked this function with selector
function(selector){
  selector.trigger('eventHere');
}

但是请注意,您必须确保selector是jQuery对象!否则,您可能会收到一条错误消息,指出trigger不是函数.

Do note however that you must ensure that selector is a jQuery object! Otherwise, you could get an error indicating that trigger is not a function.

修改

亚当·泰尔森(Adam Terlson)在注释中指出:"值得测试的是,jQuery对象是否为null或长度为0,然后对该函数执行功能.首先不执行就无法获得性能(jQuery仍会尝试)."

Adam Terlson notes in the comments "it can be worth testing if a jquery object is null or has length of 0 before execution of a function against it. Just because it won't throw an error doesn't mean that performance can't be gained by not executing it in the first place (jQuery still tries)."

还有一个 jsperf 测试表明每种技术的操作/秒都有明显的差异(不是时间!起初让我失望)-在调用函数之前先检查null/0长度的jQuery对象,而不是简单地调用功能.

There's also a jsperf test that shows that there is a discernable difference in the ops/sec for each technique (it's not time! That threw me off at first) - checking for a null/0-length jQuery object before calling the function vs. simply invoking the function.

这篇关于当找不到jQuery选择器时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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