[英]What do I wrap a document.getElementById so as not to throw a TypeError when ID can't be found?
I'm using the Hammer.js library ( http://hammerjs.github.io/ ) to enable touch gestures in a vanilla javascript environment. 我正在使用Hammer.js库( http://hammerjs.github.io/ )在原始javascript环境中启用触摸手势。 After including the library, I have a call that works on my gallery pages.
包含库之后,我将在画廊页面上进行通话。 The call fails should the id slide not be found on the page.
如果在页面上找不到ID幻灯片,则呼叫失败。 The resulting TypeError also prevents the other js for the site from being executed.
产生的TypeError还会阻止执行该站点的其他js。 I'm really new to this, but from doing some reading I think I need to wrap this code in a test so it won't run if id slide does not exist.
我真的很陌生,但是从阅读开始,我认为我需要将此代码包装在测试中,这样如果id slide不存在,它将不会运行。 Knowing how to do this will help me fix some other issues with other ids and libraries.
知道如何执行此操作将帮助我解决其他ID和库的其他问题。
So after the Hammer.js code I have my own code: 所以在Hammer.js代码之后,我有自己的代码:
var slide = document.getElementById('slide');
var mc = new Hammer(slide);
mc.on("swipeleft", function(ev) {
var url = document.querySelector('a.next').getAttribute('href');
if (url) {
window.location = url;
}
});
mc.on("swiperight", function(ev) {
var url = document.querySelector('a.prev').getAttribute('href');
if (url) {
window.location = url;
}
});
How do I prevent this code from executing if the page doesn't contain the id slide? 如果页面不包含id幻灯片,如何防止执行此代码? (and when I say it doesn't contain it, I mean that it will not exist on that page, not that the DOM isn't ready.)
(当我说它不包含它时,我的意思是它不会在该页面上存在,不是说DOM还没有准备好。)
Thanks. 谢谢。
Just test for it: 只需测试一下:
var slide = document.getElementById('slide');
if( slide ){
// .. your code
}
End the surrounding function execution if slide
is falsy: 如果
slide
虚假,则结束周围的函数执行:
var slide = document.getElementById('slide');
if (!slide) return;
//... The rest of your code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.