我无法完全考虑如何将两个几乎相同的init侦听器,jQuery函数合二为一。
VARIANT 1(可行)。 Variant №1正在运作,但它看起来很糟糕:
// Checkbox
var matchesWithEmail = document.getElementById('matchesWithEmail');
// Checkbox
var matchesWithEmail2 = document.getElementById('matchesWithEmail-2');
jQuery(matchesWithEmail).on('change', function (e) {
var current = e.target;
var checked = current.checked;
matchesWithEmail2.checked = checked;
});
jQuery(matchesWithEmail2).on('change', function (e) {
var current = e.target;
var checked = current.checked;
matchesWithEmail.checked = checked;
});
VARIANT 2(不完全可行)。 我也试图减少它,但我收到了糟糕的想法结果,它有时会给出错误的工作:
var matchesWithEmail = [document.getElementById('matchesWithEmail'), document.getElementById('matchesWithEmail-2')];
matchesWithEmail.forEach(function (element) {
jQuery(element).on('change', function (e) {
var current = e.target,
checked = current.checked,
allExceptCurrent = matchesWithEmail.filter(function (element) {
return element !== current;
});
allExceptCurrent.forEach(function (element) {
jQuery(element).off('change');
element.checked = checked;
jQuery(element).on('change', function (e) {
var current2 = e.target,
checked2 = current2.checked,
allExceptCurrent2 = matchesWithEmail.filter(function (element) {
return element !== current2;
});
allExceptCurrent2.forEach(function (element) {
jQuery(element).off('change');
element.checked = checked2;
});
});
});
});
});
请告诉我们这两个功能如何紧凑减少?
答案 0 :(得分:1)
您可以参考this
来引用创建事件的对象并获取其属性。这意味着你可以这样做:
var matches = jQuery("#matchesWithEmail, #matchesWithEmail-2");
matches.on('change', function(e) {
// set both objects to have the checked value from the one that just changed
matches.prop("checked", this.checked);
});
执行以下操作:
checked
属性设置为刚刚更改的对象(因此两个对象将相互跟踪)。checked
属性,即使不必设置当前对象。您可以使用this
过滤掉.not(this)
对象,但确实没有意义。例如,您可以这样做:代码:
var matches = jQuery("#matchesWithEmail, #matchesWithEmail-2");
matches.on('change', function(e) {
matches.not(this).prop("checked", this.checked);
});