Add one handler in terms of another?
I have a tag with a complex "oninput" handler, e.g.
<input id="x" type="text" name="x"
oninput="lotsofgeneratedcocde...."/>
I want to add another handler that simply calls that one. My initial though was that 开发者_高级运维this would work:
<input id="x" type="text" name="x"
oninput="lotsofgeneratedcocde...." onfocus="this.oninput"/>
But it doesn't. What should I be doing? Thanks.
Edit: I thought that onfocus="this.oninput" would copy the reference to the function, that's why I left off the parentheses for a call.
this.oninput()
(note parentheticals) should work:
<input id="x" type="text" name="x"
oninput="console.log('test');" onfocus="this.oninput();"/>
http://jsfiddle.net/9kNrW/
This could work?
... onfocus="this.oninput()"
I assume there's no way to have the generated code be outsourced as proper functions that you could call from both event handlers...
Short answer:
Use parens: onfocus="this.oninput();"
If oninput
references this
or the event object, you need to add a little more:
onfocus="this.oninput.call(this, event);"
Explanation:
If you were attaching the event handlers in code, your syntax is correct. Because you are setting a function reference. Ie,
myInput.onfocus = myInput.oninput;
But, when attached in the markup, the code between the quotes actually is itself a function. Eg,
<span id="foo" onclick="alert('hello world');" />
Is equivalent to:
document.getElementById("foo").onclick = function () {
alert('hello world');
};
So your code as written is the equivalent of:
document.getElementById("x").onfocus = function () {
this.oninput; // returns a function reference. Does not call the function.
};
精彩评论