这是我的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);
});
});
答案 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();