繁体   English   中英

如何 append javascript 标签内的 PHP 变量?

[英]How to append javascript variable inside PHP tag?

我正在尝试在 PHP 标签内写一个 javascript function,但我不知道确切的语法。 谁能帮忙? 我正在尝试连接名为“var1”的变量。 但我收到错误。

index.php

<?php
echo '<script>
demo(1);
function demo(var){
   const var1=1;
   const ptag=document.getElementById("content"+var1);
}
</script>';
?>

我想你想要这段代码:

<!DOCTYPE html>
<html>
<body>

<p id="content1">1th</p>
<p id="content2">2th</p>
<p id="content3">3th</p>
<p id="content4">4th</p>
<p id="content5">5th</p>


 <?php
        echo "
            <script type=\"text/javascript\">
            function demo(num){
              const paragraphTag = document.getElementById('content'+ num);
            }
            demo(1)
            </script>
        ";
  ?>

</body>
</html>

你的错误是什么:

  1. 申报后最好使用function
  2. 您不能将var用作变量的名称,它是保留键
  3. 我想你想将数字传递给 function 并使用该数字获取特定的p元素,如果是这样你就不需要var1
  4. 最后对 php echo显使用单引号" ,对content使用单引号'

也许你需要这段代码:

<!DOCTYPE html>
<html>
<body>

<p id="content1">1th</p>
<p id="content2">2th</p>
<p id="content3">3th</p>
<p id="content4">4th</p>
<p id="content5">5th</p>


<button onclick="demo()">click here</button>


 <?php
        $num = 1;
        echo "
            <script type=\"text/javascript\">
            function demo(){
              const paragraphTag = document.getElementById('content'+ $num);
              paragraphTag.textContent = 'selected'
            }
            </script>
        ";
  ?>

</body>
</html>

暂无
暂无

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

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