我应该在将功能绑定到目标元素之前测试目标元素是否存在吗? [英] should I test whether a target element exists before I bind a function to it?

查看:75
本文介绍了我应该在将功能绑定到目标元素之前测试目标元素是否存在吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的问题.想象一下,在我的网页索引上,有一个元素,我们称之为#newsletter,其中绑定了一个jquery事件.该元素在我网站的其他子页面上不存在. 现在,在我的javascript文件中,我应该将绑定限制为仅当元素存在时(用户在索引上),还是jquery自动执行此操作?

This is quite a simple question. Imagine that on the index of my webpage, there's an element, let's call it #newsletter, which has a jquery event bound to it. This element does not exist on other subpages of my site. Now, in my javascript file, should I limit the bind only to when the element exists (user is on the index), or does jquery do this automatically?

实际上,我现在拥有的是:在我的.js文件中,该功能已绑定到所有子页面上的该元素,即使该元素在那里不存在.这有问题吗?

So practically, what I have is now: in my .js file, the function is bound to that element on all subpages, even though the element does not exist there. Is this a problem?

推荐答案

从错误的角度来看,这不会有问题,因为如果没有元素与选择器匹配,那么jQuery不会抛出异常等.已经指定.

No this won't be a problem from the point of view of errors, since jQuery will not throw an exception or the like if no elements match the selectors you've specified.

但是,这可能是性能问题,具体取决于选择器表达式的复杂程度以及在不具有这些元素的页面上进行的其他此类jQuery调用的数量.如果很多,您可能希望进一步拆分JS脚本,并且每页仅加载相关的脚本.

However, this could be a performance issue depending on how complex your selector expression is and how many other such jQuery calls you make on pages that do not have those elements. If it's a lot, you might want to split up your JS scripts further and load only the relevant ones per page.

这篇关于我应该在将功能绑定到目标元素之前测试目标元素是否存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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