简体   繁体   English

错误对象没有方法

[英]Error Object has no method

My site loads dynamic js files on demand such as what pages are current displayed. 我的网站按需加载动态js文件,例如当前显示的页面。 But config file for all js libraries are every time load on every page. 但是所有js库的配置文件都是每次加载在每个页面上的。 Everything works well for a time when some library is missing. 在缺少某些库的情况下,一切运行良好。

Script stop executing on error line. 脚本停止在错误行上执行。

Sample: 样品:

$('id').library1({}); //This method doesn't exist

$('id2').library2({}); // This method is not executed

How do I execute a second object method when first object doesn't exist? 当第一个对象不存在时,如何执行第二个对象方法?

You would have to capture the error 您将必须捕获错误

try { $('id').library1({}); } catch(e){} 
$('id2').library2({}); 

or check to see if the method exists before you execute it 或在执行之前检查该方法是否存在

var elem = $('id');
if (elem.library1) elem.library1({});
$('id2').library2({}); 

Capture and log/suppress the first error you're receiving, to enable the second and any subsequent calls to be executed: 捕获并记录/抑制收到的第一个错误,以使第二个及以后的所有调用得以执行:

try{
    $('id').library1({});
}
catch(e) { console.log(e); /* capture, log, suppress error. */ }

$('id2').library2({});

Test for the existence of the method before trying to call it (and triggering an exception): 在尝试调用方法(并触发异常)之前测试该方法是否存在:

if (typeof $.fn.library1 == "function")
    $('id').library1({});
else
    ; // in case the method doesn't exist

// this method is still executed
$('id2').library2({});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM