问题
What I have:
I have two text boxes. When the page loads, the value of the first text box is applied to the second.
What I need:
I need the change event to fire when the page loads.
My code:
HTML:
a: <input type="text" id="a" value="x" />
b: <input type="text" id="b" value="y" />
JQuery:
// Apply value of #a to #b and fire change event...
$('#b').val($('#a').val()).change();
// Listen for the change and alert...
$('#b').on('change', function() {
alert("Change event fired on load.");
});
JSFiddle:
For your convenience: http://jsfiddle.net/clarusdignus/rHYLM/
My problem:
The change event is not firing.
回答1:
The event handlers are attached after the event is fired by code
First should be
// Listen for the change and alert...
$('#b').on('change', function() {
alert("Change event fired on load.");
});
// Apply value of #a to #b and fire change event...
$('#b').val($('#a').val()).change();
Second should be
// Listen for the change and alert...
$('#b').on('change', function() {
alert("Change event fired on load.");
});
// Apply value of #a to #b and fire change event...
$('#b').val($('#a').val()).trigger('change');
回答2:
You should trigger the change event. So...
$('#b').val($('#a').val()).trigger('change');
Also, you need to tell JavaScript to exec these lines after the document is loaded (ready). This can be done wrapping your code inside this:
$(function() { /* your code */ });
Wich is a simplifyed version of:
$( document ).ready(function() { ... });
来源:https://stackoverflow.com/questions/23818727/does-the-change-event-fire-on-documentready