简体   繁体   中英

Trying to add Javascript to PHP file

I am trying to add javascript to a php file and everytime I add the javascript and save, it just displays the javascript and not the rest of the page content.

The code looks like this:

<section class="portlet grid_6 leading"> 

                    <header>
                        <h2>Time <script type="text/javascript">
<!--var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
document.write(hours + ":" + minutes + " ")
if(hours > 11){
document.write("PM")
} else {
document.write("AM")
}
//-->
</script></h2>

Any suggestions?

I suppose you want to display time in that , modify your code like this.

<section class="portlet grid_6 leading"> 
<header>
    <h2>Time<span id="time_span"></span></h2>
</header>
<script type="text/javascript">
    var currentTime = new Date()
    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()
    if (minutes < 10){
        minutes = "0" + minutes
    }
    var t_str = hours + ":" + minutes + " ";
    if(hours > 11){
        t_str += "PM";
    } else {
       t_str += "AM";
    }
    document.getElementById('time_span').innerHTML = t_str;
</script>
</section>

And please next time put more effort in writing the question... formatting etc makes it easier to understand your code and question

Why not using PHP? <h2>Time <?php echo date("g:i A"); ?></h2> <h2>Time <?php echo date("g:i A"); ?></h2> (make sure you understand the difference between server time and client time)

If your JS is shown, your code is probably misinterpreted (at least not as text/html). Try removing the HTML comment sets ( <!-- & --> ).

How is this being included in your page? If you are reading it in via php (as an include or an ajax request) and using an XHTML doctype, you may need to pre-pend your Javascript with the CDATA tag (see here ) so that it is interpreted correctly.

I also +1'd @Sarvesh Kumar Singh's response as separating your function from its display makes for more readable and debugable code.

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