Javascript不能在php中工作


Javascript not working in php

大家好,我正试图将javascript嵌入到php文件导航器用户代理,但我面临这个错误:

解析错误:语法错误,unexpected '?' in/home/public_html/domain.com/modules/mod_news_pro_gk4/tmpl/layout.parts.php on line 874

代码

echo '<script  type="text/javascript">
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){
document.write('<?php return ($news_price != '') ? '<div class="nspVmStore">'.$news_price.'<span class="extxt">.00 / Only</span></div> ' : ''; ?>') ;
}
else
document.write("<?php return ($news_price != '') ? '<div class="nspVmStore">'.$news_price.'<span class="extxt">.00 / Only</span></div> ' : ''; ?>");
</script>';
<?php
$val_1 = ($news_price != '') ? '<div class="nspVmStore">'.$news_price.'<span class="extxt">.00 / Only</span></div> ' : '';
$val_2 = "value 2 here";
?>
<script  type="text/javascript">
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent))
    document.write("<?php echo $val_1;  ?>");
else
    document.write("<?php echo $val_2;  ?>");
</script>

你正在做一个带有php标签的回显。为什么不先在字符串中创建所有输出,然后再执行回显?

这里有解析错误。试试这样:

echo '
<script  type="text/javascript">
    if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){
        document.write("' . ($news_price != '' ? '<div class='"nspVmStore'">' . $news_price  . '<span class='"extxt'">.00 / Only</span></div> ' : '') . '");
    } else {
        document.write("' . ($news_price != '' ? '<div class='"nspVmStore'">'  . $news_price . '<span class='"extxt'">.00 / Only</span></div> ' : '') . '");
    }
</script>';
<?php
$news_price = 1;
?>
<script  type="text/javascript">
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){
document.write('<?=($news_price != '' ? '<div class="nspVmStore">'.$news_price.'<span class="extxt">.00 / Only</span></div> ' : ''); ?>') ;
} else {
document.write('<?=($news_price != '' ? '<div class="nspVmStore">'.$news_price.'<span class="extxt">.00 / Only</span></div> ' : ''); ?>');
}
</script>

这是工作代码:

echo '<script  type="text/javascript">
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){
    document.write("'.($news_price != '' ? '<div class="nspVmStore">'.$news_price.'<span class="extxt">.00 / Only</span></div> ' : '') .'") ;
} else {
    document.write("'.($news_price != '' ? '<div class="nspVmStore">'.$news_price.'<span class="extxt">.00 / Only</span></div> ' : '').'");
}
</script>';

你的代码很混乱,我猜你需要改变这个代码

document.write("<?php return ($news_price != '') ? "<div class='"nspVmStore'">".$news_price."<span class='"extxt'">.00 / Only</span></div>" : ''; ?>") ;

看分号