【问题标题】:Javascript: Window open and close.How to declare a window into a variable and pass to another function?Javascript:窗口打开和关闭。如何将窗口声明为变量并传递给另一个函数?
【发布时间】:2014-11-25 17:31:35
【问题描述】:

我创建了两个按钮, 打开按钮是打开子窗口。 关闭按钮是关闭子窗口。 两个按钮都位于父窗口。

这里是示例代码

$("#to-open").click(function () { 
    var popUp = window.open( _contextPath + "open.jsp","Child", "width=500, height=300").focus();
});

$("#to-close").click(function () { 
        // No sure how to get the popUp object
     //popUp.close();
    });

现在我在关闭窗口时遇到了困难。 我无法将 var popUp 传递给关闭窗口函数。 有什么建议或线索吗?

谢谢

【问题讨论】:

    标签: javascript jquery popup window


    【解决方案1】:

    只需在外部范围内声明 popUp 变量:

    var popUp;
    $("#to-open").click(function () { 
        popUp = window.open( _contextPath + "open.jsp","Child", "width=500, height=300").focus();
    });
    
    $("#to-close").click(function () { 
        if (popUp)
            popUp.close();
    });
    

    【讨论】:

    • 我通过删除 if(popUp) 来更改您的代码。 Firebug 抱怨“TypeError: popUp is undefined popUp.close();”有什么线索吗?
    • 已解决:.focus() 导致它。我把它放到一个新行中。 popUp.focus 在打开按钮。谢谢
    【解决方案2】:

    最简单的方法是将你的窗口对象放在全局对象中。

    var popUp;
    $("#to-open").click(function () { 
        window.popUp = window.open( _contextPath + "open.jsp","Child", "width=500, height=300").focus();
    });
    

    虽然这会变得很丑陋,但最好不要弄乱你的全局。

    这样的东西会更干净

    <button id="to-open">
    </button>
    <button id="to-close">
    </button>
    
    $(document).ready(function () {
        var popUp = 0;
    
        $("#to-open").click(function () { 
            popUp++;
        });
    
        $("#to-close").click(function () { 
            alert(popUp);
        });                 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多