如何在JS中使用Mobile检测PHP?

时间:2013-12-07 21:12:18

标签: javascript php jquery mobile-devices

我有一个for some reason isn't working on mobile devices的脚本。因此,我只想向移动设备显示消息。

我找到了PHP script来做这个,但我是PHP新手,不知道如何正确实现这一点。

在PHP页面中,我有以下代码:

<?php
  require_once 'Mobile_Detect.php';
  $detect = new Mobile_Detect;
?>
<!DOCTYPE html>
<html>
 <head>
   <script type="text/javascript">
     $(function() {
       if ( $detect->isMobile() ) {
         $( "body" ).prepend( "<p>You are on a mobile device.</p>" );
       }    
      });
   </script>
 </head>
 <body>
  <!-- Page Content -->
 </body>
</html>

当我运行上面的代码时,会抛出语法错误。

如果设备是移动设备,如何运行jQuery代码?

1 个答案:

答案 0 :(得分:1)

您正试图在javascript中使用php值而不将其打印到页面:

TRY

<?php if( $detect->isMobile() ) : ?>
<!-- only place script in page if it is mobile -->
<script type="text/javascript">
 $(function() {
     $( "body" ).prepend( "<p>You are on a mobile device.</p>" );
  });
</script>
<?php endif ?>