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.
<?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>
var
as a name of variable it's reserved keyp
element, if it is so you don't need var1
"
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.