Frage

I have the following script inside my Razor view :-

if (document.getElementById("currentdate") != null && document.getElementById("currenttime") != null) {
        document.getElementById("currentdate").innerHTML = EMBEDformatAMPM();

what i am doing is the folloiwng :-

  • Since the currentdate & currenttime are only displayed if the user is authenticated . so if the element is not displayed the getElementById.innerHTML will raise a reference exception. so that why i decide to check if these elements exists or not before setting their .innerHTML. My checking is working well on IE and chrome, while on firefox the current date and time will not be displayed even if the currentdate and currenttime DOM elements exists

.. can anyone advice please ?

Edit Here is the generated HTML:-

<section id="login" class="navbar-search pull-right">
  <span class="username customTopNavText " style=" display:block; ">
      [<a href="/tms/Account/LogOff/" style="color:white"> Logout </a>]
      <i class="icon-user"></i> <strong >   </strong>
  </span>
  <div  class="customTopNavText" id="currentdate"></div>
  <div  class="customTopNavText" id="currenttime" ></div>   
      <form class="customSearch"method="GET" action="/tms/Home/Search">
          <input  class="push-up-button searchmargin" placeholder="Search by tag.." name="searchTerm2" data-autocomplete-source= "/tms/Home/AutoComplete" type="text" style="margin-top:8px"/><input type="submit" value="Search" class="btn" />
      </form>
</section>

<div class="top-nav nav-collapse">
    <ul class="nav">
        <li class="customTitle" style= "color:#f99406">TMS - Staging  </li>
        <li></li>
    </ul>
</div><!--/.nav-collapse -->

</div>
</div>

</div>

where both the currentdate & currenttime are there , but their HTML is not being set using the following script:-

    var el = document.getElementById('currentdate');
    if (el != null) {
        //if (document.getElementById("currentdate") != null && document.getElementById("currenttime") != null) {
        document.getElementById("currentdate").innerHTML = EMBEDformatAMPM();
        var myVar = setInterval(function () { myTimer() }, 30000);

        function myTimer() {
            document.getElementById("currentdate").innerHTML = EMBEDformatAMPM();
        }
        function EMBEDformatAMPM() {
            var d = new Date(),
                minutes = d.getMinutes().toString().length == 1 ? '0' + d.getMinutes() : d.getMinutes(),
                hours = d.getHours().toString().length == 1 ? '0' + d.getHours() : d.getHours(),
                ampm = d.getHours() >= 12 ? 'pm' : 'am',
                months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
                days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
            return days[d.getDay()] + ' ' + d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear();
        }
        document.getElementById("currenttime").innerHTML = EMBEDformatAMPM2();

        var myVar2 = setInterval(function () { myTimer2() }, 30000);
        function myTimer2() {
            document.getElementById("currenttime").innerHTML = EMBEDformatAMPM2();
        }
        function EMBEDformatAMPM2() {
            var d = new Date(),
                minutes = d.getMinutes().toString().length == 1 ? '0' + d.getMinutes() : d.getMinutes(),
                hours = d.getHours().toString().length == 1 ? '0' + d.getHours() : d.getHours(),
                ampm = d.getHours() >= 12 ? 'pm' : 'am',
                months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
                days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
            return hours + ':' + minutes;
        }
    }

Thanks

War es hilfreich?

Lösung

Firefox generally chokes with hoisting function declarations in blocks... You can try a simple example yourself:

if (true) {
    execute();
    function execute() { alert("worked"); } 
}

The above works in Chrome and IE but doesn't in FF (although there is an error). Try putting the declaration of EMBEDformatAMPM outside of your if:

function EMBEDformatAMPM() {
    var d = new Date(),
        minutes = d.getMinutes().toString().length == 1 ? '0' + d.getMinutes() : d.getMinutes(),
        hours = d.getHours().toString().length == 1 ? '0' + d.getHours() : d.getHours(),
        ampm = d.getHours() >= 12 ? 'pm' : 'am',
        months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    return days[d.getDay()] + ' ' + d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear();
}

var el = document.getElementById('currentdate'); 
if (el != null) {       
        el.innerHTML = EMBEDformatAMPM();
}

I may be a being slightly unfair to say that FF chokes - according to the spec the only thing allowed within a block are statements and a function declaration is not a statement.

You may also want to head over to code review as there are several things in your code that could be improved.

Edit (replying to comments)

It's not a bug with Firefox as what you are doing is not technically allowed according to the specification. Chrome and IE are being more permissive by making a good guess at what you want but there's no guarantee that it will work in future versions.

As to improvements to your code, check out this fiddle

// wrap in IIFE to avoid polluting global namespace.
(function () {
   // declare all our variables at the top of the function
    var currentDate = document.getElementById('currentdate'),
       currentTime = document.getElementById('currenttime'),
       updateTime,
       getFormattedDate,
       getFormattedTime;

    // Give functions names that make their purpose clear
    getFormattedDate = function() {
            var d = new Date(),
                months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
                days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
            return days[d.getDay()] + ' ' + d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear();       
    };
    getFormattedTime = function () {
            var d = new Date(),
                minutes = d.getMinutes().toString().length == 1 ? '0' + d.getMinutes() : d.getMinutes(),
                hours = d.getHours().toString().length == 1 ? '0' + d.getHours() : d.getHours();
            return hours + ':' + minutes;
    };

    // This function updates the time and then 
    // sets a timeout to execute again after 3 seconds.
    updateTime = function () {
        if (currentTime !== null && currentDate !== null) {
            currentTime.innerHTML = getFormattedTime();
            currentDate.innerHTML = getFormattedDate();
        }
        window.setTimeout(updateTime, 3000);
    };
    // Start it off.
    updateTime();
}());
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top