如何根据屏幕大小在js中声明php echo值?

时间:2018-04-13 06:49:35

标签: javascript php

我试图在js中回显php值。我们的想法是根据屏幕尺寸显示有限的值。这是代码;

    <?php
        foreach( $data as $row ){
 $path1 ="
<tr>
<td><strong>Name</strong></td>
<td><strong>Price (USD)</strong></td>
<td>{$row['name']}</td>
<td>{$row['price']}</td>
</tr> 
";
 $path2 ="
<tr>
<td><strong>Rank</strong></td>
<td><strong>Name</strong></td>
<td><strong>Price (USD)</strong></td>
<td>{$row['rank']}</td>
<td>{$row['name']}</td>
<td>{$row['price']}</td>
</tr>
";
}?>


<script>
window.onload = function() {
if (screen.width < 960) 

   document.getElementById("phone").innerHTML = "<?php echo $path1; ?>";
else

    document.getElementById("phone").innerHTML = "<?php echo $path2; ?>";
}
</script>

<body>
    <div>
        <span id ="phone"></span>

    </div>
</body>

在运行时,窗口中没有响应(空白)。为什么我要回显这些值是因为$ path1和$ path2将具有从api派生的值,这将在表中生成多个行和列。当屏幕尺寸较小(移动)时,我试图提供有限的数据列。

感谢任何帮助。

RGDS。

1 个答案:

答案 0 :(得分:0)

Try this one with template:

   <?php

$path1 = '';
$path2 = '';
foreach( $data as $row ){
$path1 .=
'<tr>
<td><strong>Name</strong></td>
<td><strong>Price (USD)</strong></td>
</tr> 
';

$path2 .=
'<tr>
<td><strong>Rank</strong></td>
<td><strong>Name</strong></td>
<td><strong>Price (USD)</strong></td>
</tr>';

}
?>


<script>
window.onload = function() {
if (screen.width < 960) 

   document.getElementById("phone").innerHTML = `<?php echo $path1; ?>`;
else

    document.getElementById("phone").innerHTML = `<?php echo $path2; ?>`;
}
</script>

<body>
    <div>
        <span id ="phone"></span>