jquery 等待更改事件 [英] jquery wait on change event

查看:27
本文介绍了jquery 等待更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 jQuery 构建了一个动态表单;当第一个选择输入(名为 category)更改时,第二个选择输入(名为 subcategory)会与子选择项一起出现.这现在很完美.

With jQuery I built a dynamic form; when the first select-input (named category) changes a second select-input (named subcategory) appears with sub-select items. And this works perfect now.

当给出特定的 url 参数时,我想在页面准备好后自动填写表单.

When a specific url parameter is given I want to auto-fill in the form after the page is ready.

$(document).ready(function () {
    // initialize defaults
    var category = getUrlParameter('category');
    var subcategory = getUrlParameter('subcategory');
    if (category && subcategory) {
        $("select#category").val(category).change();
        $("select#subcategory").val(subcategory).change();
    }
});

其中 getUrlParameter 是我从 Sameer Kazi 复制的辅助函数.

Where getUrlParameter is a helper function I copied from Sameer Kazi.

目前第一个select-input已经填好,第二个select-input已经生成但没有填入.所以实际上change命令需要等到第一个change命令准备好.

Currently the first select-input is filled in, the second select-input is generated but not filled in. So actually, the change command needs to wait untill the first change command is ready.

推荐答案

你可以使用 jQuery 的 .when() 函数,该函数先before .then() 被调用.

You can using jQuery's .when() function, which handles an asynchronous function first before .then() is called.

$.when($("select#category").val(category).change()).then(function() {
  $("select#subcategory").val(subcategory).change();
});

下面是一个使用这两个函数的小例子.我在选择更改事件处理程序中添加了一个 console.log 函数,以便您可以了解发生的情况.

Here below is a small example using those two functions. I have added a console.log function to the select change event handlers so that you can follow what happens.

$("select#category").on('change', function() {
  console.log('[on change] category changed');
  $("select#subcategory").show();
});

$("select#subcategory").on('change', function() {
  console.log('[on change] subcategory changed');
});

$(document).ready(function () {
    // initialize defaults
    var category = 1;
    var subcategory = 2;
    if (category && subcategory) {
        $.when($("select#category").val(category).change()).then(function() {
            console.log('[then] activating subcategory');
            $("select#subcategory").val(subcategory).change();
        });
    }
});

select#subcategory {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="category">
 <option>...</option>
 <option value="1">value 1</option>
 <option value="2">value 2</option>
</select>
 
 <select id="subcategory">
   <option value="1">subvalue 1</option>
   <option value="2">subvalue 2</option>
 </select>

这篇关于jquery 等待更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆