页面重新加载后进行onclick事件操作

时间:2009-07-07 16:16:07

标签: javascript prototypejs

我有Javascript打开另一个窗口并为所有链接注册一个点击处理程序:

//Inside a class somewhere
this.file_browser_window = $(window.open("/filebrowser", "file_browser_window",
        "width=800,height=600"))

Event.observe(this.file_browser_window, 'load', function (){
     //This is the event I am after
     Event.observe(this.file_browser_window, 'click', handle_click_in_browser);
}.bindAsEventListener(this));

// The Handler function
function handle_click_in_browser(evt){
   evt.stop();  

   url = evt.target.href;

   if(url && url.endsWith('.png')){
       console.log("Image clicked");
       //REMMEMBER THIS URL ON MAIN PAGE
       this.close();
   }
   else{
       console.log("Regular stuff clicked", this);
       this.location = url; //<-- THIS is the breaking point
   }
}

但是,当用户点击该弹出窗口中的某个链接时,当页面重新加载时,我的CLICK处理程序就会消失!

弹出窗口中的链接指向同一个域。

现在,我无法更改弹出窗口中的源(html)。我需要捕获用户点击的链接标记的href(如果它指向图像)。

如果有人有兴趣,我会在弹出窗口中运行django-filebrowser

2 个答案:

答案 0 :(得分:1)

您可以通过在新的弹出窗口中将文件浏览器页面放在iframe中来解决此问题。我可能会回来编辑这段代码,但是现在这里有一些代码可能会让你开始(可能不会按原样运行 - 不经测试就这样做)

== Page你正在从===========

启动弹出窗口
// some code to launch the file browser wrapper popup
var file_browser_popup = $(window.open("/new_wrapper_page.html", "file_browser_popup",
                "width=800,height=600"));

==内部new_wrapper_page.html ===========

<html>
<head>
<script type="text/javascript">
// most of your existing code stays the same, but things are moved around

function listenForClicks() {
    var ifrm = $('filebrowser_iframe');
    var content = (ifrm.contentWindow ? ifrm.contentWindow.document : (ifrm.contentDocument ? ifrm.contentDocument : null));
    if (content) {
        //This is the event I am after
        Event.observe(content, 'click', handle_click_in_browser);
    }

}

// The Handler function
function handle_click_in_browser(evt){
   evt.stop();  

   url = evt.target.href;

   if(url && url.endsWith('.png')){
       console.log("Image clicked");
       //REMEMBER THIS URL ON MAIN PAGE
       parent.close();
   }
   else{
       console.log("Regular stuff clicked", this);
       parent.location = url; //<-- THIS is the breaking point
   }
}
</script>
</head>
<body>
<iframe id="filebrowser_iframe" src="/filebrowser/" width="800" height="600" onload="listenForClicks();"/>
</body>
</html>

无论如何,这是可以玩的东西。如果您需要更多指导,请告诉我 - 我的Prototype技能很弱,而且我只使用您现有的代码来弄清楚您究竟要做什么......

答案 1 :(得分:0)

您应该在弹出页面本身内为弹出页面应用您的点击事件处理程序。我没有看到任何理由让父窗口负责这些事件处理程序。

相关问题