如果条件为true,如何停止执行javascript
How to stop execution of javascript if condition is true?
我想用一个特定的URL来标记我的移动访问者,比如http://www.example.com.index.html?source=mobile我使用这个脚本将访问者重定向到给定的url
<script type="text/javascript">
<!--
if (screen.width <= 800)
{
window.location ="http://www.example.com/index.html?source=mobile";
}
//-->
</script>
但当我使用这个脚本时,页面一次又一次地加载,所以我试图在这个脚本中添加另一个条件,但我不知道如何使第二个条件停止加载。
<script type="text/javascript">
<!--
if (screen.width >= 800)
{
window.location ="http://www.example.com/index.html?source=mobile";
}
Else if (document.referrer ="http://www.example.com/index.html?source=mobile")
{
//stop execution here
}
//-->
</script>
现在,如果第二个条件为真,请有人帮我停止执行javascript。
提前谢谢。
将语句包装在匿名函数中:
(function(){
if (screen.width >= 800) {
window.location = "http://www.example.com/index.html?source=mobile";
}else if (document.referrer == "http://www.example.com/index.html?source=mobile") {
return;
}
});
您只能在函数中使用return,而不管其他答案是怎么说的。
我还假设您将在if语句下面添加更多的代码,否则停止执行是没有用的。
你的代码有几个问题:
- 您用大写E拼写else,is应为小写
- 在else-if语句中,您没有使用两个等号
这两个问题都在上述代码中进行了修订
怎么样
if (screen.width >= 800 && document.referrer !="http://www.example.com/index.html?source=mobile")
{
window.location ="http://www.example.com/index.html?source=mobile";
}
你现在设置它的方式不会像第一个那样起作用。如果总是满足的话,你应该按照我在这里的建议做,或者把文档引用条件放在第一个(加上你需要==不=)。
你应该直接在php/whateveryouuse中检测移动浏览器,有很多移动检测器脚本(检查用户代理如何检查请求是否来自php中的移动或计算机)
现在的方式是:用户进入网站,如果分辨率低,他会被重定向到…同一个页面!(两次加载站点)
如果检测到移动服务器端:用户只进入站点一次<--更快,即使javascript被禁用也能工作
此外,如果您只关心浏览器的分辨率
使用window.location.href
获取URL
你有一个打字错误:else if
。。不是Else if
if (screen.width >= 800 && window.location.href !="http://www.example.com/index.html?source=mobile")
{
window.location.href ="http://www.example.com/index.html?source=mobile";
}
在停止执行的情况下,
else if (window.location.href ="http://www.example.com/index.html?source=mobile")
{
return;//to stop execution here..use return;
}
// This condition is unnecessary though
注意:return true,return false and return
之间存在差异
return false:停止事件"冒泡"。停止执行
返回true:继续执行。
返回
这里引用了ECMA262标准中关于返回的一句话,JavaScript是基于该标准的;如前所述,结果是"未定义的"。
如果ECMAScript程序包含一个不在FunctionBody中的返回语句。A.return语句导致函数停止执行并返回值。如果省略了Expression,则返回值为未定义。否则,返回值为Expression的值。
IE8、IE8+、IE11、Firefox、Chrome:
<script>
... I wana cancel here ...
if (document.execCommand) document.execCommand('Stop');
if (window.stop) window.stop();
</script>
- 如果条件匹配,则停止执行脚本
- 停止执行,直到jquerypost完成
- 如何在更改window.location后停止执行
- 无法运行安卓.bat文件.xcopy 命令停止执行
- iFrame在超时时停止执行
- 停止执行某些 JavaScript 代码
- 阻止“停止执行此脚本”消息
- 如果初始事件返回 false,则停止执行事件侦听器
- IE 在使用 clientscript.registerstartup 调用处理程序之前停止执行 JavaScript
- Phantomjs 脚本在 JSON 对象解析后停止执行
- 代码过早停止执行
- 如何在 JavaScript 中 x 毫秒后停止执行用户代码
- IndexedDB.open 在 Safari iOS 8.1.1 上返回 null,并在 Cordova 上停止执行.
- Firefox 上的 Javascript 在 onchange 任务上意外停止执行
- JavaScript:回调,不会停止执行下面的行
- 如何在点击后停止执行javascript
- 为什么 JavaScript 代码在 for 循环后停止执行
- jQuery 停止执行,直到调度事件
- 在 jQuery 中完成之前停止执行另一个
- Javascript/jQuery返回false不会停止执行