The js code is in the footer and when the div is not on the page it shows an error. This only happens when i'm using $('id-of-the-div')
not $$('#id-of-the-div')
. And the error stop the hole script.
Js code
window.addEvent('domready', function() {
$('id-of-the-div').addEvent('click', function() {
alert('click');
});
});
Error
Uncaught TypeError: Cannot call method 'addEvent' of null
an element reference returns an object or null. if null, it won't be truthy. you can check for that like you would for any property of the current context object:
pattern one:
var el = $('someel');
if (el) {
el.addEvent({ ... });
}
// or
if (!el) return;
// or
el && el.addEvent({ });
pattern 2, use event delegation by assigning the event to a parent element
$('main').addEvent('click:relay(#otherid)', function(event, otherel){
});
pattern 3: collections don't iterate when no items:
$$('#someid').addEvent('click', fn);
when not found, the above won't call the addEvent at all.
pattern 1 is the most common
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.