Javascript onclick(如果存在iframe),将其删除并创建新的iframe?

时间:2018-12-11 04:42:08

标签: javascript jquery html

这是我的JavaScript代码,用于创建iframe,如何执行onclick(如果存在iframe,将其删除并创建新的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);
    });
});

3 个答案:

答案 0 :(得分:3)

您可以在添加avgames之前清除innerHTML = "";,如下所示。清除iframe中现有的avgames。之后,您append新建一个。

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);
    });
});

答案 1 :(得分:1)

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>

答案 2 :(得分:1)

我的第二个解决方案! :)

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