javascript - 如何减少重复的 jquery 代码
问题描述
jQuery('#edit-field-number-of-beneficial-owner-und').change(function() {
if (jQuery(this).val() == 0) {
jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-one').nextUntil('.form-actions').find('input, select, textarea').val('');
jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-one').nextUntil('.form-actions').find('input:checkbox').attr('checked', false);
jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-one').nextUntil('.form-actions').find('select').trigger("chosen:updated");
} else if (jQuery(this).val() == 1) {
jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-two').nextUntil('.form-actions').find('input, select, textarea').val('');
jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-two').nextUntil('.form-actions').find('input:checkbox').attr('checked', false);
jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-two').nextUntil('.form-actions').find('select').trigger("chosen:updated");
} else if (jQuery(this).val() == 2) {
jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-three').nextUntil('.form-actions').find('input, select, textarea').val('');
jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-three').nextUntil('.form-actions').find('input:checkbox').attr('checked', false);
jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-three').nextUntil('.form-actions').find('select').trigger("chosen:updated");
}
});
解决方案
正如所指出的,简化代码的主要是将中间步骤存储在变量中。我想在数据结构中添加封装条件检查:
jQuery('#edit-field-number-of-beneficial-owner-und').change(function() {
const $this = jQuery(this);
const labels = ['one', 'two', 'three'];
const target = $this.parent()
.parent('#edit-field-number-of-beneficial-owner')
.siblings(`#edit-field-beneficial-owner-${labels[+$this.val()]}`)
.nextUntil('.form-actions');
target
.find('input, select, textarea')
.val('');
target
.find('input:checkbox')
.attr('checked', false);
target
.find('select')
.trigger('chosen:updated');
});
推荐阅读
- chef-infra - 使用 Chef 安装 mtputty 时如何创建桌面图标?
- .net - 如何访问具有多个应用程序的身份服务器?
- java - Appium TestNG 测试:无法从二级菜单列表中选择:NoSuchElementException
- angular - 使用 rxjs 进行 Mat-sort 无法正常工作
- php - WooCommerce - 自定义库存状态和可变产品
- php - 基于从选项字段中选择的选项从数据库表列中获取变量到输入字段
- android - 模拟器不断重启Android Studio 3.1.4?
- multithreading - 一个进程如何使用套接字处理 Web 服务器上的多个请求?TCP
- javascript - 如何使用节点 js 生成 cookie?
- google-cloud-platform - 谷歌云永久磁盘中的根永久磁盘和非根永久磁盘