【问题标题】: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>
我尝试用 <![if !IE 8]> 包围该脚本,但 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。