¿Cuál es la forma correcta de usar window.opener de Javascript?
-
28-10-2019 - |
Pregunta
He creado una ventana emergente y en ella me gustaría usar una función que he creado en la ventana principal.Intenté usar window.opener.parentFunction () pero para saberlo.¿Alguien más ha experimentado este problema?Así es como se ve mi código.
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);
}
* Lo tengo funcionando.Gracias chicos.
Solución
Hay muchos problemas con su código.He preparado una demostración funcional aquí .
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
no se definió -
this.getCols()
no se definió -
parentFunction
(probablemente) no era visible en el ámbito dewindow
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow