简体   繁体   English

如何在php标签内编写javascript

[英]how to write javascript inside php tag

I am trying to write a javascript inside php tags my javascpript is here 我正在尝试在php标签内编写一个javascript,我的javascpript在这里

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

and what I am doing is here 我在做什么

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

what is wrong here? 这是怎么了

Your script tag is just like any other HTML tag, just close your PHP tag before opening it: 您的脚本标签与任何其他HTML标签一样,只需在打开之前关闭PHP标签即可:

?>

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

<?php

what I was doing wrong is , I was echoing the js in parts. 我做错的是,我在部分回显了js。 What I needed to was something like this 我需要的是这样的东西

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

whole js in just 1 peice is the key here. 整个js只需1 peice是这里的关键。

I'm guessing the reason you are echoing javascript via php is that u want to be able to generate dynamically the number you add to the end of the image source/src tag. 我猜测您通过php回显javascript的原因是您希望能够动态生成您添加到图像源/ src标记末尾的数字。 you can do it as follows... 您可以按照以下步骤进行操作...

As far as your php file is saved with extension of '.php' you can do this without errors: 只要您的php文件以'.php'扩展名保存,您就可以做到:

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

And that is it, just use the php open and closing tag where u need to output something dynamic... other than that, leave pure javascript out side to avoid confusion. 就是这样,只需在您需要输出动态内容的地方使用php打开和关闭标签即可,除此之外,请保留纯JavaScript以避免混淆。 Make sure u provided a link to jquery library as well as i can see that from your syntax u intend to use jquery. 确保您提供了指向jquery库的链接,以及我可以从您的语法中看到您打算使用jquery。 hope this helps. 希望这可以帮助。 :-) :-)

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

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