且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当找不到jQuery选择器时会发生什么?

更新时间:2022-06-15 01:02:20

关于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.