如何防止第一次onclick执行

时间:2012-05-24 10:13:17

标签: javascript

我正在编写一个javascript函数,动态创建一个iframe,如果按下该按钮可以删除其iframe。

这些是我的javascript函数:

 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中的按钮?

提前致谢。

2 个答案:

答案 0 :(得分:2)

您需要将函数处理程序而不是函数调用结果传递给onclick属性。

您可以使用匿名函数执行此操作:

butt.onclick = function() { removeIframe(iframeName); };

答案 1 :(得分:2)

onclick必须是一个函数,替换以下行

butt.onclick = removeIframe(iframeName);

butt.onclick = function() { removeIframe(iframeName); }