should I test whether a target element exists before I bind a function to it?
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 m开发者_高级运维y javascript file, should I limit the bind only to when the element exists (user is on the index), or does jquery do this automatically?
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?
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.
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.
You won't get any errors because an invalid selector in jQuery is OK. It just won't assign the event handler to it.
As for performance, it shouldn't matter because the selector will be parsed anyway if you wanted to do something like this...
var element = $('#some .complex selector:first > :last-child');
if (element.length) {
element.click(doIt);
}
However, it may make more sense if you are doing more code inside of the check for the element's existence.
There is no need of checking whether an element exists or not, when using jQuery. You may bind any function/event to any element, and those functions will work when that element is present in DOM.
If that element, say #newsletter, does not exist in the DOM, then jQuery will just skip binding your function and will not throw any exception. It is 100% safe when you use jQuery.
When you use a selector in jQuery, it actually returns a jQuery object, and not a javascript element. Your events are binded to a jQuery object.
Hope that makes it clear.
精彩评论