如果IE8如何不运行javascript

时间:2013-11-04 19:44:00

标签: javascript jquery html internet-explorer-8

我有一个搜索字段验证,如果浏览器是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>

我尝试用<![if !IE 8]>围绕该脚本,但Dreamweaver说这是错误的。

3 个答案:

答案 0 :(得分: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;
});

功能检测/渐进增强是跨浏览器不一致的更首选方法。

答案 1 :(得分:2)

<!--[if !IE 8]-->
<script>
    ...
</script>
<!--[endif]-->

答案 2 :(得分:0)

您可以尝试此操作,但请使用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