使用document.write在PHP中编写JS

时间:2013-07-04 15:33:47

标签: php javascript document.write

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

我有一个php数组:

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

这是为了知道哪些页面有旋转木马并且需要触摸支持。

所以我在php中查看页面,如果列出了JS,它将检查其触摸设备并编写addional 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>';
}
?>

3 个答案:

答案 0 :(得分:1)

你的问题就在这里,我想:

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
}
?>

答案 1 :(得分:1)

在页面加载后使用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);
}

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

答案 2 :(得分:0)

不确定您的问题是否包含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
}
?>

尝试一下:)