正确嵌套这个JS

时间:2013-01-07 17:57:24

标签: javascript

我有这个针对JS的移动userAgent测试,并且我不太确定如何正确嵌套以扩展测试。

基本上现在它测试移动或桌面,我希望它进一步做的是移动,检查哪些移动和做某事。

<script type="text/javascript">
  if( /Android|iPhone|iPod|iPad|BlackBerry|Windows Phone/i.test(navigator.userAgent) ) {
    if ( /Android/i.test(navigator.userAgent) ) {
        var url = window.location.href = 'http://www.google.com';
        url.show(); 
    }
    elseif 
    if ( /iPhone/i.test(navigator.userAgent) ) {
        var url = window.location.href = 'http://www.bing.com';
        url.show(); 
    }
  }
    else
  {

  }
</script>

我知道上面的内容是错误的,但就我而言,它已经设法解决了。

2 个答案:

答案 0 :(得分:0)

不是重复自己,而是可以做这样的事情:

if( /big regex here/i.test(navigator.userAgent)) {
    var agents = {
        "Android":"http://google.com/",
        "iPhone":"http://bing.com/"
    }, i, url;
    for( i in agents) {
        if( new Regexp(i,"i").test(navigator.userAgent)) {
            url = window.location.href = agents[i];
            url.show();
            break;
        }
    }
}

答案 1 :(得分:0)

下面

<script type="text/javascript">
  var url="notmobile.html";
  if( /Android|iPhone|iPod|iPad|BlackBerry|Windows Phone/i.test(navigator.userAgent) ) {
    if ( /Android/i.test(navigator.userAgent) ) {
        url = 'http://www.google.com';
    }
    else if ( /iPhone/i.test(navigator.userAgent) ) {
        url = 'http://www.bing.com';
    }
//   url.show(); // some special mobile meaning? - never seen that syntax
    location=url; // this is how I would do it
  }
  else { // not mobile
    // this can be moved out side the ifs with the above location change too
    location = url;
  }
</script>