首页 > 解决方案 > 如何减少重复的 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");
  }
});

标签: javascriptjqueryfunction

解决方案


正如所指出的,简化代码的主要是将中间步骤存储在变量中。我想在数据结构中添加封装条件检查:

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');
});

推荐阅读