繁体   English   中英

如何在php标签内编写javascript

[英]how to write javascript inside php tag

我正在尝试在php标签内编写一个javascript,我的javascpript在这里

<script>  
    $('#img').attr("src","getImage.php?id="+);
    $('#img').show();
</script>

我在做什么

   <?php
    echo "<script>";  
    echo " $('#img').attr(\"src\",\"getImage.php?id=\"+1); ";
    echo " $('#img').show(); ";
    echo "</script>";
    ?>

这是怎么了

您的脚本标签与任何其他HTML标签一样,只需在打开之前关闭PHP标签即可:

?>

<script>  
    $('#img').attr("src", "getImage.php?id=" + 1);
    $('#img').show();
</script>

<?php

我做错的是,我在部分回显了js。 我需要的是这样的东西

    <?php
    echo " <script>  
    $('#img').attr(\"src\",\"getImage.php?id=\"+2);
    $('#img').show();
    </script> ";
    ?>

整个js只需1 peice是这里的关键。

我猜测您通过php回显javascript的原因是您希望能够动态生成您添加到图像源/ src标记末尾的数字。 您可以按照以下步骤进行操作...

只要您的php文件以'.php'扩展名保存,您就可以做到:

<?php $n = 2; //Declaration of n ?>
<script>
$("#img").attr("src", <?php echo "\"getImage.php?id=$n\"" ?>);
$("#img").show();
</script>

就是这样,只需在您需要输出动态内容的地方使用php打开和关闭标签即可,除此之外,请保留纯JavaScript以避免混淆。 确保您提供了指向jquery库的链接,以及我可以从您的语法中看到您打算使用jquery。 希望这可以帮助。 :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM