2017-03-17 91 views
-1

有很奇怪的。它看起来像在If语句之后,它停止的脚本。该页面具有通过单击按钮调用的javascript函数。如果IE上的浏览器,我会做点什么。否则,我关闭该页面。我把警报声明来测试它。但警报从未解雇。有人会告诉我我的代码会出现什么问题。之后如果声明什么都不会在javascript中触发

还有就是我的按钮调用该函数:

<input class="btn" id="btnClose" onclick="javascript:openFile();" type="button" value="Close" name="btnClose" /> 

有JavaScript函数:

function openFile() { 

      var url = 'file://' + document.getElementById("hdURL").value; 
      //alert('Open File' + url); 
      var location = document.getElementById("hdURL").value; 

      ////http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser 
      if ((/*@[email protected]*/false || !!document.documentMode) ||(!isIE && !!window.StyleMedia)) 
      { 
       alert('IE'); 
       //do something 
       window.self.close(); 
      } 
      alert('test'); //never fire 

      closeWindow(); 

     } 
+3

''不something' - 这是应该是一个评论?如果是这样,它应该是'//做些事情'。 – Santi

+1

我看不到'isIE'在哪里定义。看看你的浏览器控制台。你在那里看到错误吗? – Amy

+0

@Amy这是一个很好的观点。看看[引用的问题OP](http:// stackoverflow。com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser)为他们的'if'逻辑,接受答案使用'var isIE =(...逻辑...) '。 OP复制+粘贴该逻辑并将其用作上述问题中他们的'if'语句的第一个条件,而不是像引用的答案那样将其转换为var'isIE'。 – Santi

回答

1

首先,要给予信贷上的问题的意见Amy实现你的isIE未定义。


看看the question you referenced在您的代码中接受的答案。它说以下内容:(我已经添加的箭头以示出使用isIE

// Internet Explorer 6-11 
var isIE = /*@[email protected]*/false || !!document.documentMode; 
// |________  
//    | 
// Edge 20+ V 
var isEdge = !isIE && !!window.StyleMedia; 

通知如何其用于检测边缘引用变量,用于检测IEisIE例子。在你的例子中,你没有var isIE,所以这是未定义的 - 代码失败。


为什么它在IE浏览器而不是火狐/ Chrome浏览器?

如果第一个条件成立,JavaScript将不会评估OR的第二个条件 - 这就是所谓的Short Circuit Evaluation

使用IE时,第一个条件的计算结果为true。这意味着第二个条件(和其中的语法错误)被忽略为

但是,Chrome和Firefox在第一种情况下获得false,并且必须评估第二种情况。一旦他们到达未定义的变量,就会抛出一个错误。


解决方案:

// Internet Explorer 6-11 
var isIE = /*@[email protected]*/false || !!document.documentMode; 

// Edge 20+ 
var isEdge = !isIE && !!window.StyleMedia; 

if (isIE || isEdge) { 
    //DO STUFF 
} 
+0

我怎样才能让艾米得分?谢谢你们所有人 – user819774

+0

没必要。如果我想要我可以自己回答的代表。我很高兴Santi回答并得到了一些代表。分享爱。 – Amy

0

它总是有帮助的准备jsifddle,这样你就可以立即测试您的解决方案,并看到错误。 这也是最好检查一下浏览器控制台,显示错误

看到工作示例

https://jsbin.com/sipukovono/edit?html,css,js,console,output

function openFile() { 

var isIE=false; // temporary definition 

var url = 'file://' + document.getElementById("hdURL").value; 
     //alert('Open File' + url); 
     var location = document.getElementById("hdURL").value; 


     if ((false || !!document.documentMode) ||(!isIE && !!window.StyleMedia)) 
     { 
      alert('IE'); 
      window.self.close(); 
     } 
     alert('test'); //never fire 

     closeWindow(); 

    } 
+0

我不确定“这里有一个错误,只是将它设置为”false“而忘记它是一个优雅的解决方案。 – Santi

+0

我想这个变量将在检查它是什么浏览器后设置。 使用jsbin用户的工作代码现在可以进行必要的修改和测试。正如我们可以看到原始问题那样,确定代码已损坏并不容易。 – plusz

相关问题