Jquery 更改事件是否在documentready上触发? 我所拥有的:

Jquery 更改事件是否在documentready上触发? 我所拥有的:,jquery,onchange,document-ready,Jquery,Onchange,Document Ready,我有两个文本框。加载页面时,第一个文本框的值将应用于第二个文本框 我需要的是: 我需要在页面加载时触发更改事件 我的代码: HTML: a: <input type="text" id="a" value="x" /> b: <input type="text" id="b" value="y" /> // Apply value of #a to #b and fire change event... $('#b').val($('#a').val()).change

我有两个文本框。加载页面时,第一个文本框的值将应用于第二个文本框

我需要的是: 我需要在页面加载时触发更改事件

我的代码: HTML:

a: <input type="text" id="a" value="x" />
b: <input type="text" id="b" value="y" />
// 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:

a: <input type="text" id="a" value="x" />
b: <input type="text" id="b" value="y" />
// 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.");
});
为方便起见:

我的问题是:
更改事件未触发。

您应该触发更改事件。所以

$('#b').val($('#a').val()).trigger('change');
此外,您还需要告诉JavaScript在加载文档(准备就绪)后执行这些行。这可以通过将代码包装在以下内容中完成:

$(函数(){/*您的代码*/})

Wich是以下内容的简化版本:

$(文档).ready(函数(){…})


事件处理程序在代码触发事件后附加

首先应该是

  // 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();
// 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');
第二个应该是

  // 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();
// 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');

不需要
.trigger()
-
.change()
也能正常工作,我知道,但这个想法是为了让Clarus知道他需要触发一个事件处理程序。我已经应用了
.trigger()
,但没有效果。请查看这个分叉JSFIDLE:关于您的编辑,是的,我的本地代码已经包装在必要的函数中。i、 e.
jQuery(document).ready(function($){
。根据我提供的JSIDdles,据我所知,它会自动应用document ready函数。@tymeJV-请参考我问题中提供的JSIDdle..change()没有产生想要的效果。谢谢。这是有效的,警报框现在正在生成。