我如何退出JavaScript脚本,就像PHP的退出或死亡?我知道这不是最好的编程实践,但我需要这样做。
当前回答
在我的例子中,我使用window.stop。
window.stop()在当前浏览上下文中停止进一步的资源加载,相当于浏览器中的'stop'按钮。 由于脚本的执行方式不同,此方法不能中断其父文档的加载,但它将停止其父文档的图像、新窗口和其他仍在加载的对象。 用法:window.stop (); (源)
其他回答
JavaScript相当于PHP的die。顺便说一句,它只是调用exit()(谢谢splattne):
function exit( status ) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brettz9.blogspot.com)
// + input by: Paul
// + bugfixed by: Hyam Singer (http://www.impact-computing.com/)
// + improved by: Philip Peterson
// + bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
// % note 1: Should be considered expirimental. Please comment on this function.
// * example 1: exit();
// * returns 1: null
var i;
if (typeof status === 'string') {
alert(status);
}
window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);
var handlers = [
'copy', 'cut', 'paste',
'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
];
function stopPropagation (e) {
e.stopPropagation();
// e.preventDefault(); // Stop for the form controls, etc., too?
}
for (i=0; i < handlers.length; i++) {
window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true);
}
if (window.stop) {
window.stop();
}
throw '';
}
这个小函数非常接近于模仿PHP的exit()。与其他解决方案一样,不要添加任何其他解决方案。
function exit(Msg)
{
Msg=Msg?'*** '+Msg:'';
if (Msg) alert(Msg);
throw new Error();
} // exit
如果你不关心它是一个错误,可以这样写:
fail;
这将阻止您的主(全局)代码继续进行。 对调试/测试的某些方面很有用。
这是一个例子, 如果条件存在,则终止脚本。 我使用这个在我的SSE客户端javascript,如果
<script src="sse-clint.js" host="https://sse.host" query='["q1,"q2"]' ></script>
不能直接从JSON解析…
if( ! SSE_HOST ) throw new Error(['[!] SSE.js: ERR_NOHOST - finished !']);
... 总之,总的思想是:
if( error==true) throw new Error([ 'You have This error' , 'At this file', 'At this line' ]);
这将终止/死亡你的javascript脚本
在我的例子中,我使用window.stop。
window.stop()在当前浏览上下文中停止进一步的资源加载,相当于浏览器中的'stop'按钮。 由于脚本的执行方式不同,此方法不能中断其父文档的加载,但它将停止其父文档的图像、新窗口和其他仍在加载的对象。 用法:window.stop (); (源)
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?