Javascript 如何防止第一次onclick执行
我正在编写一个javascript函数,该函数动态创建一个带有按钮的Iframe,如果按下该按钮,可以删除其Iframe 以下是我的javascript函数:Javascript 如何防止第一次onclick执行,javascript,Javascript,我正在编写一个javascript函数,该函数动态创建一个带有按钮的Iframe,如果按下该按钮,可以删除其Iframe 以下是我的javascript函数: function createIframe (iframeName, width, height) { var iframe; if (document.createElement && (iframe = document.createElement('iframe'))) { ifra
function createIframe (iframeName, width, height) {
var iframe;
if (document.createElement && (iframe = document.createElement('iframe'))) {
iframe.name = iframe.id = iframeName;
iframe.width = width;
iframe.height = height;
var connectIP = document.getElementById("ip").value;
var connectPORT = document.getElementById("port").value;
iframe.src = "http://"+connectIP+":"+connectPORT;
document.body.appendChild(iframe);
addElement(iframe.name);
}
return iframe;
}
function removeIframe(iframeName) {
iframe = document.getElementById(iframeName);
if (iframe) {
var x=iframe.parentNode.removeChild(iframe)
}
}
function addElement(iframeName) {
var butt = document.createElement('button');
var butt_text = document.createTextNode('Remove');
butt.appendChild(butt_text);
butt.onclick = removeIframe(iframeName);
document.body.appendChild(butt);
}
问题是,当创建按钮时,onclick函数会立即执行,而不仅仅是在用户按下它时执行,因此我的新Iframe会立即被删除,而我看不到它
我怎样才能解决这个问题
此外,是否可以将按钮不添加到父实体中,而是直接添加到新创建的iframe中
提前感谢。您需要将函数处理程序而不是函数调用结果传递给
onclick
属性
您可以使用匿名功能执行此操作:
butt.onclick = function() { removeIframe(iframeName); };
您需要将函数处理程序而不是函数调用结果传递给
onclick
属性
您可以使用匿名功能执行此操作:
butt.onclick = function() { removeIframe(iframeName); };
onclick必须是一个函数,替换以下行
butt.onclick = removeIframe(iframeName);
与
onclick必须是一个函数,替换以下行
butt.onclick = removeIframe(iframeName);
与
如何添加按钮???@gsagrawal:*如何,*是,*你,-?相关(但上下文略有不同):。。。这个问题在这里经常出现。你是如何添加按钮的?@gsagrawal:*如何,*是,*你,-?相关的(但上下文略有不同):。。。不过,这个问题在这里经常出现。