简体   繁体   中英

After changing innerHTML, page automatically reloads?

I'm trying to make a simple JavaScript/HTML page that inserts an audio player after being given a URL. Every time I press the button that the code below generates, the audio player is inserted, and then the page seems to refresh, getting rid of that HTML.

HTML:

<div id="titleBlock">
    <h4>Livestream Listener</h4>
    <p>Enter a livestream URL below so you can listen in-browser.</p>
    <form>
        <input id="stream" type="url">
        <button onclick="livestreamlisten()" class="btn">Listen</button>
    </form>
</div>
<hr />
<div id="streamBlock">
</div>

JS:

function getStreamURL(){
    var stream = document.getElementById('stream').value;
    return stream;
}

function insertPlayer(url){
    var html = `
        <audio controls>
            <source src="${url}" type="audio/mpeg">
            <source src="${url}" type="audio/ogg">
        </audio>
    `;
    document.getElementById("streamBlock").innerHTML = html;
}

function livestreamlisten(){
    var url = getStreamURL();
    insertPlayer(url);
}

You need to make the button be a simple button, not a "submit" button:

<button type="button" onclick="livestreamlisten()" class="btn">Listen</button>

Alternatively you could just get rid of the surrounding <form> .

Either do what @Pointy suggested, or pass the event object to your livestreamlisten(event) function and call event.preventDefault() inside it like so:

 function getStreamURL(){ var stream = document.getElementById('stream').value; return stream; } function insertPlayer(url){ var html = ` <audio controls> <source src="${url}" type="audio/mpeg"> <source src="${url}" type="audio/ogg"> </audio> `; document.getElementById("streamBlock").innerHTML = html; } function livestreamlisten(event){ event.preventDefault(); // prevent the default behavior of "reloading" var url = getStreamURL(); insertPlayer(url); } 
 <div id="titleBlock"> <h4>Livestream Listener</h4> <p>Enter a livestream URL below so you can listen in-browser.</p> <form> <input id="stream" type="url"> <button onclick="livestreamlisten(event)" class="btn">Listen</button> </form> </div> <hr /> <div id="streamBlock"> </div> 

I hope that helps!

You should add a return false; to the livestreamlisten() function, to prevent the button from doing it's default action. Without it, you will get side-effects like form submissions, etc. This also applies to anchor tags <a> , eg, links that should fire a function on click.

The method becomes:

function livestreamlisten(){
    var url = getStreamURL();
    insertPlayer(url);
    return false;
}

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