Does the change event fire on documentready?

烂漫一生 提交于 2019-12-11 13:53:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!