在 php 代码中调用 javascript 元素


Calling javascript elements within php code

如果 JavaScript 元素在标签内,可以识别它们吗?所以比如:

<?php
  $username = "maniacal";
  echo "<p class='welcome' id='greeting'>Hi, Welcome to the site!!</p>"
?>

这就是我的php的样子。然后我可以从代码的另一部分调用"greeting"元素,例如document.getElementById('greeting').innerHTML='Greetings ' + name + '!';

是的,你可以例如。

 <?php
   $username = "maniacal"; 
   echo"<p class='welcome' id='greeting'>Hi, Welcome to the site!!</p>" ;
?>
<script>
  document.getElementById('greeting').innerHTML="Hi <?php echo $username?>, welcome to the site";
</script>

是的,你可以做到,但你应该在document.ready标签中添加你的javascript代码,因为你的

<p class='welcome' id='greeting'>Hi, Welcome to the site!!</p>

应该放在你的html页面上,然后再通过-->getElementById

请尝试以下代码:

使用 PHP :

 $username = "maniacal"; 
 echo"<p class='welcome' id='greeting'>Hi, "$username" Welcome to the site!!</p>" ;

或使用Javascript:

<script>
  document.getElementById('greeting').innerHTML="Hi <?php echo $username?>, welcome to the site";
</script>