在jQuery中,尝试绑定事件处理程序之前检查元素是否存在更快吗? [英] In jQuery, is it faster to check if an element exists before trying to bind event handlers?

查看:48
本文介绍了在jQuery中,尝试绑定事件处理程序之前检查元素是否存在更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先检查元素是否存在,然后绑定事件处理程序,这样更快吗?

Is it faster to first check if an element exists, and then bind event handlers, like this:

if( $('.selector').length ) {
    $('.selector').on('click',function() {
          // Do stuff on click
    }
}

还是简单地做一下更好?

or is it better to simply do:

$('.selector').on('click',function() {
     // Do stuff on click
}

所有这些都在准备好文档时发生,因此延迟越短越好.

All this happens on document ready, so the less delay the better.

推荐答案

只需使用

$('.selector').on('click',function() {
     // Do stuff on click
}

如果类selector中不存在任何元素,则jQuery将完全不绑定任何内容.

If no elements exist with the class selector, jQuery will simply not bind anything.

这篇关于在jQuery中,尝试绑定事件处理程序之前检查元素是否存在更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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