3 回答
![?](http://img1.sycdn.imooc.com/533e4c640001354402000200-100-100.jpg)
TA贡献1864条经验 获得超2个赞
正如所指出的,简化代码的主要内容是将中间步骤存储在变量中。我想在数据结构中添加封装条件检查:
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');
});
![?](http://img1.sycdn.imooc.com/5333a1d100010c2602000200-100-100.jpg)
TA贡献1831条经验 获得超10个赞
有很多方法可以处理这个问题。这是一个例子。
将您的值 0-2 映射到等效的字符串中。使用该值作为数组的索引来获取字符串(注意允许您使用模板文字的反引号)。将一长串 jQuery 调用存储到一个变量中,并使用该变量进行find()调用。
jQuery('#edit-field-number-of-beneficial-owner-und').change(function() {
let ownerMap = ['one', 'two', 'three']
let owner = jQuery(this).val()
let formAction = jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings(`#edit-field-beneficial-owner-${ownerMap[owner]}`).nextUntil('.form-actions')
formAction.find('input, select, textarea').val('');
formAction.find('input:checkbox').attr('checked', false)
formAction.find('select').trigger("chosen:updated")
});
![?](http://img1.sycdn.imooc.com/5458655200013d9802200220-100-100.jpg)
TA贡献1784条经验 获得超7个赞
使用局部变量作为您正在处理的所有事物的“基础”的结果。然后,您可以创建一个函数来处理您重复输入的步骤。
jQuery('#edit-field-number-of-beneficial-owner-und').change(function() {
let numOwner = jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner');
let handle = function(sibs) {
sibs.nextUntil('.form-actions').find('input, select, textarea').val('');
sibs.nextUntil('.form-actions').find('input:checkbox').attr('checked', false);
sibs.nextUntil('.form-actions').find('select').trigger("chosen:updated");
}
if (jQuery(this).val() == 0) {
handle(numOwner.siblings('#edit-field-beneficial-owner-one'))
} else if (jQuery(this).val() == 1) {
handle(numOwner.siblings('#edit-field-beneficial-owner-two'))
} else if (jQuery(this).val() == 2) {
handle(numOwner.siblings('#edit-field-beneficial-owner-three'))
}
});
添加回答
举报