我在页面上有按钮可以激活和停用设置。 ID 是相同的条形,它们的前缀,例如我有"#rl-激活"、"#rl-停用"、"#cl-激活"、"#cl-停用" 有没有办法重构此代码,所以我不会为页面上的每个按钮执行此操作。
// rl activate
$('#rl-activate').click(function(){
$('#rl-activate').hide();
$('#rl-deactivate').show();
$('#rl').val(50).prop('selected', true);
$('#rl').prop('disabled', false).trigger('liszt:updated');
displayCPM();
newPrice();
checkSettings();
});
// rl deactivate
$('#rl-deactivate').click(function(){
$('#rl-deactivate').hide();
$('#rl-activate').show();
$('#rl').prop('disabled', true).trigger('liszt:updated');
$('#rl').val('').trigger('liszt:updated');
displayCPM();
newPrice();
checkSettings();
});
因此,对于下一个,所有更改都将是rl到cl到bm等
你可以
这样做:
$('[id$="-activate"]').click(function(){
var prefix = this.id.slice(0,2);
$(this).hide();
$('#'+prefix+'-deactivate').show();
$('#'+prefix).val(50).prop('selected', true);
$('#'+prefix).prop('disabled', false).trigger('liszt:updated');
displayCPM();
newPrice();
checkSettings();
});
$('[id$="-deactivate"]').click(function(){
var prefix = this.id.slice(0,2);
$(this).hide();
$('#'+prefix+'-activate').show();
$('#'+prefix).prop('disabled', true).trigger('liszt:updated');
$('#'+prefix).val('').trigger('liszt:updated');
displayCPM();
newPrice();
checkSettings();
});
这使用"属性结尾为"选择器。
另一种解决方案是更改 HTML 以使用类("激活"、"停用")和数据属性("cl"、"rl")。
遵循 DRY 原则,您可以将一些代码分解到一个通用函数中,使用 jQuery 在自己的代码中大量使用的复制样式,并更多地利用 jQuery 链接:
function clickCommon(itemToHide, itemToShow) {
$(itemToHide).hide()
$(itemToShow).show();
displayCPM();
newPrice();
checkSettings();
}
["#rl", "#cl"].each(function(pref) {
$(pref + "-activate").click(function() {
clickCommon(this, pref + "-deactivate");
$(pref).val(50).prop('selected', true)
.prop('disabled', false).trigger('liszt:updated');
});
$(pref + "-deactivate").click(function() {
clickCommon(this, pref + "-activate");
$(pref).prop('disabled', true).trigger('liszt:updated');
.val('').trigger('liszt:updated');
});
});
使用的技术:
- 将激活和停用点击之间的通用代码分解为通用功能
- 使用
.each()
从数组迭代前缀(jQuery 在其实现中内部做了很多) - 尽可能使用
this
,而不是重新查找当前元素 - 在代码中为每个前缀构造激活和停用 id 值
- 对在公共 jQuery 选择器上调用的所有方法使用 jQuery 链接