简体   繁体   中英

Javascript onclick if iframe exists, remove it and create new iframe?

This is my javascript code to create iframe , how I can do it, onclick if iframe exists, remove it and create a new iframe ?

window.addEventListener('load', function CreateIframe() {
    $(document).on('click', '.row a', function(e) {
        e.preventDefault();
        link = $(this).attr('href');
        document.getElementById("avgames").style.display = "block";
        var iframe = document.createElement('iframe');
        iframe.frameBorder = 0;
        iframe.width = "75%";
        iframe.height = "620";
        iframe.maxHeight = "100%";
        iframe.id = "randomid";
        iframe.setAttribute("src", link);
        document.getElementById("avgames").appendChild(iframe);
    });
});

You may clear your avgames before append using innerHTML = ""; like below. Its clear the existing iframe inside avgames . After that you append new one.

window.addEventListener('load', function CreateIframe() {
    $(document).on('click', '.row a', function(e) {
        e.preventDefault();
        link = $(this).attr('href');
        document.getElementById(desireID).innerHTML = "";
        document.getElementById("avgames").style.display = "block";
        var iframe = document.createElement('iframe');
        iframe.frameBorder = 0;
        iframe.width = "75%";
        iframe.height = "620";
        iframe.maxHeight = "100%";
        iframe.id = "randomid";
        iframe.setAttribute("src", link);
        document.getElementById("avgames").appendChild(iframe);
    });
});

 window.addEventListener('load', function CreateIframe(){ $(document).on('click', '.row a', function(e) { if($('body iframe').length){ $('body iframe').remove(); e.preventDefault(); link = $(this).attr('href'); document.getElementById("avgames").style.display = "block"; var iframe = document.createElement('iframe'); iframe.frameBorder=0; iframe.width="75%"; iframe.height="620"; iframe.maxHeight="100%"; iframe.id="randomid"; iframe.setAttribute("src", link); document.getElementById("avgames").appendChild(iframe); } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

My second Solution! :)

  $('iframe').not(this).remove();

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