【问题标题】:How to not run javascript if IE8 [duplicate]如果 IE8 [重复],如何不运行 javascript
【发布时间】:2013-11-04 19:43:59
【问题描述】:

如果浏览器是 IE8,我没有运行搜索字段验证。

这是我的 javascript:

<script type="text/javascript">
    jQuery("#mini-search-form").submit(function() {
        var match =/[a-zA-Z0-9]+/.exec(jQuery('#mini-search-form #query').val());
      if(!match){
        alert("Please enter valid search words.");
        return false;
      }
      return true;
    });
</script>

我尝试用 &lt;![if !IE 8]&gt; 包围该脚本,但 Dreamweaver 说这是错误的。

【问题讨论】:

标签: javascript jquery html internet-explorer-8


【解决方案1】:
<!--[if !IE 8]-->
<script>
    ...
</script>
<!--[endif]-->

【讨论】:

    【解决方案2】:

    根据用户的浏览器代理选择性地运行代码并不是最佳做法。话虽如此,以下是粗略的解决方案:

    if(window.navigator.userAgent.indexOf('MSIE 8') == -1){
        jQuery("#mini-search-form").submit(function() {
            var match =/[a-zA-Z0-9]+/.exec(jQuery('#mini-search-form #query').val());
            if(!match){
                alert("Please enter valid search words.");
                return false;
            }
            return true;
    });
    

    特征检测/渐进增强是解决跨浏览器不一致问题的更优选方法。

    【讨论】:

      【解决方案3】:

      你可以试试这个但使用feature detection instead of browser detection(如果不仅与IE-8有关)

      <!--[if !(IE 8)]><!-->
      <script>
          jQuery(function(){
              jQuery("#mini-search-form").submit(function() {
                  var match =/[a-zA-Z0-9]+/.exec(jQuery('#mini-search-form #query').val());
                  if(!match){
                      alert("Please enter valid search words.");
                      return false;
                  }
                  return true;
              });
          });
      </script>
      <!--<![endif]-->
      

      阅读About conditional comments

      【讨论】:

      • 任何反对票的理由都会让我知道其中的区别。
      猜你喜欢
      • 2013-09-17
      • 2013-03-05
      • 2019-10-14
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      相关资源
      最近更新 更多