我用jQuery打开一个窗口。然后我想关闭它,但window.close或nameOfTheWindow.close不起作用。我该怎么办?
我在这里有一个例子:http://jsfiddle.net/D99Gk/2/
HTML:
<a class="open" href="http://www.google.com" target="_blank"> open window 1 </a>
<br><br>
<a class="close" href="#"> close window 1</a>
JQUERY:
$(function(){
//I give the window the name window1 and I open it:
$('.open').click(function(e){
e.preventDefault();
window.open("","window1","width=400, height=400");
});
$('.close').click(function(){
// I tried and does not work:
// window.close();
// window1.close();
});
})
答案 0 :(得分:3)
像这样:
$(function(){
var popup;
$('.open').click(function(e){
e.preventDefault();
popup = window.open("","window1","width=400, height=400");
});
$('.close').click(function(){
if(popup) popup.close();
});
});
答案 1 :(得分:2)
$(function(){
var winref;
$('.open').click(function(e){
e.preventDefault();
winref = window.open("","window1","width=400, height=400");
});
$('.close').click(function(){
winref.close();
});
});
注意:正如A. Wolff所做的那样,您应该检查winref
:
$('.close').click(function(){
if (winref) winref.close();
});
这是为了防止错误在winref
存在之前或关闭之前首次点击关闭链接。
答案 2 :(得分:1)
试试这个:
$(function(){
var wi = null;
$('.open').click(function(e){
e.preventDefault();
wi = window.open("","window1","width=400, height=400");
});
$('.close').click(function(){
wi.close();
});
})
<强> Demo 强>