ajouter un événement à un cadre en utilisant la syntaxe en ligne:Enregistrement de l'événement onload pour un cadre à l'aide addEventListener/attachEvent
<FRAME SRC="s.htm" NAME="WINCONTENT" onload="alert(this)">
Cela fonctionne (= l'événement se déclenche chaque fois qu'une nouvelle URL est chargée), sauf que je préfère enregistrer des événements en utilisant addEventListener
/attachEvent
.
Maintenant, dans l'exemple onload="alert(this)
, this
est défini sur HTMLFrameElement. Comment accéder à HTMLFrameElement depuis JavaScript? (je besoin de le préciser comme argument pour addEventListener
/attachEvent
)
Notez que parent.WINCONTENT
et le point comme à un objet fenêtre alors ce que je dois est HTMLFrameElement. J'ai fait des recherches sur google, mais apparemment, les cadres ont été démodés pendant un certain temps.
listes complètes ci-dessous:
index.htm
<HTML>
<HEAD>
<TITLE>WINMAIN</TITLE>
</HEAD>
<FRAMESET COLS=255,*>
<FRAME SRC="frm_navi.htm" NAME="WINNAVI">
<FRAME SRC="s.htm" NAME="WINCONTENT" ID="WINCONTENT">
</FRAMESET>
</HTML>
frm_navi.htm
<HTML>
<HEAD>
<TITLE>Navigation Pane</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript" SRC="dom.js"></SCRIPT>
</BODY>
</HTML>
s.htm
<HTML>
<HEAD>
<TITLE>CONTENTS</TITLE>
</HEAD>
<BODY>
<P><A HREF="r.htm">r.htm</A></P>
<P><DIV ID="test">Click me, the event handler was registered in JavaScript</DIV></P>
</BODY>
</HTML>
r.htm
<HTML>
<HEAD>
<TITLE>CONTENTS</TITLE>
</HEAD>
<BODY>
<P>This file s.htm</P>
</BODY>
</HTML>
dom.js
function register_event (_target, _ename, _func) {
if(! _target) {
return false;
}
// Required for accessing <this> inside the event handling function.
_target[_func] = _func;
if (_target.addEventListener) {
_target.addEventListener(
_ename,
function(e) { _target[_func](e);},
false
);
}
else if (_target.attachEvent) {
_target.attachEvent(
"on" + _ename,
function(e) { _target[_func](e);}
);
}
else {
return false;
}
return true;
};
function handle_event () {
alert("Event handler registered in JS.");
};
register_event(parent.WINCONTENT.document.getElementById("test") , "click", handle_event);
register_event("_what_do_i_enter_here_ ???", "load", handle_event);
J'ai ajouté des inscriptions (vérifié dans FF) Le bit manquant du puzzle est dans la dernière ligne: "_what_do_i_enter_here_ ???" – user292152
WHOA, les travaux suivants register_event (parent.document.getElementById ("WINCONTENT"), "load", handle_event); K. – user292152