繁体   English   中英

按钮的onclick在HTML文件中有效,但在PHP文件中的HTML中无效

[英]Onclick of button works in HTML file but does not work in HTML inside a PHP file

我对PHPJSHTML还是陌生 ,所以希望您不要介意这个问题很琐碎。 因此,我基本上有以下代码, onlick可以在单独的HTML文件中工作,但是如果我将其放在PHP文件的回声中或放在PHP文件中的单独html块中,则onlick

button.html(有效)

   <body>


        <p>Click the button to display the time.</p>

        <button onclick="getElementById('demo').innerHTML=Date()">What is the time?</button>

        <p id="demo"> </p>

    </body>

</html>

这是回显代码:

button.php(无效)

<?php
....
....
echo "

        <input type ='button' value = 'Date'  onclick = 'getElementById('demo')=Date();' /> 

        <p id='demo'> </p>

        "
?>

这是PHP文件中无效的HTML代码。

button.php(无效)

<?php>

?>

<html>
<body>

<p>Click the button to display the time.</p>

<button onclick="getElementById('demo').innerHTML=Date()">What is the time?</button>

<p id="demo"></p>

</body>
</html>

任何帮助,将不胜感激!

一次回声尝试一下

echo ' <input type ="button" value = "Date"  onclick = "getElementById('demo')=Date();" />';

单撇号和双撇号有时会导致错误,PHP无法理解这是什么

HTML页面上不能有两个具有相同ID的元素。 请尝试以下代码。

<html>
  <body>
     <p>Click the button to display the time.</p>
     <button onclick="getElementById('demo').innerHTML=Date()">What is the time?</button>

     <p id="demo"> </p>
     <?php 
        echo ' <input type ="button" value = "Date"  onclick = getElementById("demo").innerHTML=Date(); />';  
     ?>
  </body>
</html>

还如@WTFZane所提到的,单撇号和双撇号有时会导致错误,PHP无法理解这是什么。

这就是我尝试过的希望对您有所帮助

 <!DOCTYPE html> <html> <body> <h1>My First JavaScript</h1> <button type="button" onclick="document.getElementById('date_time_button').innerHTML = Date()"> Click and see Date and Time.</button> <p id="date_time_button"></p> </body> </html> 

您不能在字符串内写与包含字符串相同的引号。

您需要使用\\字符对引号进行转义,如下所示:

echo "

        <input type ='button' value = 'Date'  onclick = \"getElementById('demo')=Date();\" /> 

        <p id='demo'> </p>

        ";
?>

回声线需要一个; 为了结束它;-)

PHP报价问题的脸在这里。 我认为您在这里可能会错(“演示”)。

<p id="demo"> </p> 
<button onclick="getElementById('demo').innerHTML=Date()">What is the time?</button>

用此代码替换

<?php echo '<p id="demo"> </p><button onclick="getElementById(\'demo\').innerHTML=Date()">What is the time?</button>';?> 

暂无
暂无

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

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