使用document.write在PHP中编写JS


Writing JS in PHP with document.write

这是失败的,但我不知道如何让它工作。

我有一个php数组:

$swipe_list = array('customers.html', 'index.html', 'atr_backplane.html');

这是为了了解哪些页面有转盘,需要触摸支持。

所以我在php中检查页面,如果它被列出,JS将检查它的触摸设备,并编写附加的JS移动文件。

是因为服务器脚本试图在js能够在客户端检测到之前运行吗??

<?php
if(in_array($selected, $swipe_list)){ ?>
<script type="text/javascript">
function isTouchDevice(){ document.write('<script type="text/javascript" src="js/jquery.mobile.custom.min.js"></script>')
}
</script>            
<?php }?>
<?php if(!in_array($selected, $exclude_list)){       
print '<script type="text/javascript" src="js/camera.js"></script>';
}
?>

当您在页面加载后使用document.write时,可能会发生各种不好的事情。我不记得确切的原因,但我知道它以某种方式破坏了DOM。

最好的方法是在不破坏DOM的情况下动态地包含脚本,而是使用以下内容:

function isTouchDevice(){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'js/jquery.mobile.custom.min.js';
    document.getElementsByTagName('head')[0].appendChild(script);
}

这将创建script元素并将其附加到文档的头部。

我认为您的问题在于:

function isTouchDevice(){ document.write('<script type="text/javascript" src="js/jquery.mobile.custom.min.js"></script>')
}

这条线没有任何作用的原因有很多。

首先,定义了函数isTouchDevice,然后从未调用(至少在您的示例中没有)

其次,在文档加载后将文本写入文档并不是加载外部脚本的可行方法。

据我所知,你想这样做:(如果您不喜欢这种方法,也可以使用php的printecho函数将脚本标记打印到文档中)

<?php
if(in_array($selected, $swipe_list))
{ 
?>
   <script type="text/javascript" src="js/jquery.mobile.custom.min.js"></script>
<?php 
}
if(!in_array($selected, $exclude_list))
{
?> 
   <script type="text/javascript" src="js/camera.js"></script>
<?php
}
?>

不确定你的问题是否是包含js文件,但我认为如果你只是删除document.write并包含你的脚本,那么它应该可以工作:

    <?php
if(in_array($selected, $swipe_list)){ ?>
  <script type="text/javascript" src="js/jquery.mobile.custom.min.js"></script>
<?php
} 
if(!in_array($selected, $exclude_list)){       
?>
   <script type="text/javascript" src="js/camera.js"></script>
<?php
}
?>

尝试一下:)