如何链接jQuery onchange事件之类的? [英] how to chain jQuery onchange event like?
问题描述
input#one
input#two
input#three
$('#one').change(function() {
$('#two').val('change_by_one');
});
$('#two').change(function() {
$('#three').val('changed');
});
我想链接更改事件,所以当我更改#one
时,它将先更改#two
然后#three ...
我尝试过
I want to chain the change event, so when I change #one
, it will change #two
then #three ...
I tried
$('#one').change(function() {
$('#two').val('change_by_one');
// at this point, the changed value of `#two` is not rendered yet, resulting some invalid state.
$('#two').trigger('change');
});
任何想法如何实现?连锁事件
Any idea how to achieve that? Chain events
==============更新=============== 一个更好的例子是我的问题:
==============update=============== a better example to my issue is:
<select id="organisation">
<option value="org1">org1</option>
<option value="org2">org2</option>
</select>
<select id='media'>
</select>
<input placeholder="get the selected media"/>
var $media = $('#media');
$('#organisation').change(function() {
var options = [];
setTimeout(function() {
$media.append('<option value="image" data-type="image">image</option>');
$media.append('<option value="first" data-type="video">video</option>');
}, 1000);
$media.change();
});
$('#media').change(function() {
$('input').val($('#media').val());
});
选择组织执行ajax调用以获取其媒体文件,并在媒体选择中呈现选项,我只想在组织更改时触发一些媒体字段的onchange事件.
Select organisation do ajax call to get it's media files, and render the options in the media select, I just want some onchange event for media field triggered when organisation is changed.
我有个例子. https://jsfiddle.net/rht3Lxav/
=============解决方案=========
============= solution ==========
var $media = $('#media');
$('#organisation').change(function() {
var options = [];
AddOptions().then(function() {
$media.change();
});
});
$('#media').change(function() {
$('input').val($('#media').val());
});
function AddOptions() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
$media.find('option').remove().end();
$media.append('<option value="image" data-type="image">image</option>');
$media.append('<option value="first" data-type="video">video</option>');
resolve();
}, 1000);
});
};
谢谢!
推荐答案
您可以这样做:
$('#one').change(function() {
$('#two').val('change_by_one').change();
});
$('#two').change(function() {
$('#three').val('change_by_two').change();
});
$('#three').change(function() {
$('#four').val('change_by_three');
});
您可以在此处进行测试: https://jsfiddle.net/m2gb3yj1/9/
You can test it here : https://jsfiddle.net/m2gb3yj1/9/
这篇关于如何链接jQuery onchange事件之类的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!