简体   繁体   中英

How to append javascript variable inside PHP tag?

I am trying to write a javascript function inside PHP tag, but I do not know the exact syntax. Can anyone help? I am trying to concat the variable named "var1". But I am getting error.

index.php

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

I think you want this code:

<!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>

what is your mistakes:

  1. it's better to use function after declaration
  2. you can't use var as a name of variable it's reserved key
  3. I think you want to pass number to function and use that number for getting specific p element, if it is so you don't need var1
  4. finally use single quotes " for the php echo and single quotes ' for content

and maybe you need this code:

<!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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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