使用Javascript的window.opener的正确方法是什么?

时间:2011-03-22 13:50:45

标签: javascript popupwindow window.opener

我已经创建了一个弹出窗口,在其中我想使用我在父窗口中创建的函数。我已经尝试过使用window.opener.parentFunction()但是知道了。还有其他人遇到过这个问题吗?这是我的代码的样子。

function parentFunction(){
alert('testing');
}


function print(){
var new_win = window.open('','name','height=400,width=500');
var output = "<html><head></head><body><table>\n";


for (i = 0; i < 10; i++) {
output += "<td onclick='window.opener.parentFunction()'>"+i+"</td>";
}

output += "</table></body></html>\n";
new_win.document.write(output);
}

*搞定了。谢谢你们。

1 个答案:

答案 0 :(得分:4)

您的代码存在许多问题。我已经整理了一个有效的演示here

HTML

<button id="clickMe">Click me</button>

的JavaScript

window.onload = function() {

    function parentFunction() {
        alert('testing');
    }

    window.parentFunction = parentFunction;

    var years = [1, 2, 3, 4, 5, 6];

    function print() {
        var new_win = window.open('', 'name', 'height=400,width=500');
        //var cols = this.getCols();
        var cols = 2;
        var output = "<html><head></head><body><table>";
        var cell_count = 1;
        for (i = 0; i < years.length; i++) {
            if (cell_count === 1) {
                output += "<tr>";
            }
            output += "<td onclick='window.opener.parentFunction();'>" + years[i] + "</td>";
            cell_count++;
            // end the row if we've generated the expected number of columns
            // or if we're at the end of the array
            if (cell_count > cols || i === years.length - 1) {
                output += "</tr>\n";
                cell_count = 1;
            }
        }
        output += "</table></body></html>";
        new_win.document.write(output);
    }

    document.getElementById('clickMe').onclick = print;
};
  • years未定义
  • this.getCols()未定义
  • parentFunction(可能)在window范围内
  • 不可见
相关问题