问题
I want to run a function when a HTML <input/>
tag changes. How do I do this? There are some answers for this but they are all in jQuery and I want plain javascript. Can someone give me a simple example? Thanks!
I want the input to be a type as text:
<input type="text" id="change">
回答1:
You can use the input event. This will trigger not only on key up and paste, but also other text modification events such as drag & drop.
change.addEventListener("input", function (e) {
alert(this.value);
});
<input type="text" id="change">
回答2:
Use addEventListener
:
document.getElementById('change').addEventListener("keyup", function (evt) {
console.log(this.value);
}, false);
Demo: http://jsfiddle.net/tusharj/y9xcoqja/
Docs: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
The
EventTarget.addEventListener()
method registers the specified listener on theEventTarget
it's called on. The event target may be an Element in adocument
, theDocument
itself, aWindow
, or any other object that supports events (such asXMLHttpRequest
).
EDIT
To bind multiple events on the same element:
var element = document.getElementById('change');
function myEventHandler(event) {
}
element.addEventListener("keyup", function (evt) {
myEventHandler(evt);
}, false);
element.addEventListener("change", function (evt) {
myEventHandler(evt);
}, false);
来源:https://stackoverflow.com/questions/30806948/javascript-run-function-on-input-change-no-jquery