简体   繁体   中英

Putting a link after document.getElementById('').innerHTML =

I have made a countdown timer and after it is done, I want it to show
"Completed, click here to continue."
Click here should be a hyperlink. But I don't know how to do this.
The Javascript timer:

var seconds = initialTime;
function timer() {
    var days        = Math.floor(seconds/24/60/60);
    var hoursLeft   = Math.floor((seconds) - (days*86400));
    var hours       = Math.floor(hoursLeft/3600);
    var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
    var minutes     = Math.floor(minutesLeft/60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds; 
    }
    document.getElementById('countdown').innerHTML = minutes + "minutes " + remainingSeconds+ "seconds";
    if (seconds == 0) {
        clearInterval(countdownTimer);
        document.getElementById('countdown').innerHTML = "Completed"; //Link should be shown after completed here
    } else {
        seconds--;
    }

Also this is the html code where the live countdown and Completed+hyperlink should be shown:

<p class="p-2" style="font-family:R;">You can visit the site again in <span id="countdown" class="timer"></span></p>

innerHTML means just that: Inner HTML . If you know how to create a link using HTML, just assign that HTML.

document.getElementById('countdown').innerHTML = 'Completed, <a href="https://your-link-goes-here/">click here</a> to continue';

As a side note: I'm constantly seeing people here on Stack Overflow using innerHTML as the default and only way to add content to an element, even when they're just putting plain text into an element.

There's a another property, innerText , that's much better suited for that, and you don't have to worry that text will accidentally be treated as HTML or HTML entities.

You need the insertAdjacentText() function I believe you need it right after your countdown then the 'beforeend' would do.

Example:

  document.getElementById("countdown").insertAdjacentHTML("beforerend", "<p>My new paragraph</p>");

Here is the full documentation on the aforementioned function

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText

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