XUL textbox addEventListener
I'm trying to detect when a user hits escape or enter when in a xul textbox (firefox extension). But the following code doesn't seem to work. Any assistance would be much appreciated.
const KEY_ENTER = 13;
const KEY_ESCAPE = 27;
function ke开发者_JAVA百科yPressed(e) {
switch (e.keyCode) {
case KEY_ENTER:
// do something
break;
case KEY_ESCAPE:
// do something
break;
}
}
var textbox = document.getElementById("mytextbox");
textbox.addEventListener('keypress', keyPressed, true);
Are you running this script before the textbox has been inserted in the document? This example works fine for me:
<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/javascript"><![CDATA[
window.addEventListener("load", function() {
const KEY_ENTER = 13;
const KEY_ESCAPE = 27;
function keyPressed(e) {
switch (e.keyCode) {
case KEY_ENTER:
alert('enter');
break;
case KEY_ESCAPE:
alert('escape');
break;
default:
alert('default');
break;
}
}
var textbox = document.getElementById("mytextbox");
textbox.addEventListener('keypress', keyPressed, true);
alert('there');
}, false);
]]></script>
<textbox id="mytextbox" value="stuff"></textbox>
</window>
I'm also a little curious why you're passing true
as the capturing argument when adding the listener. Generally you want to do stuff in the bubbling phase when handling events, not the capturing phase (i.e. after listeners on more-specific descendants of the element where you're listening have been called).
精彩评论