无法将两个 jQuery 函数缩减为一个函数

Can't to reduce two jQuery functions into one function

我想不出如何将两个几乎相同的初始化侦听器 jQuery 函数合并为一个。

变体 1(可行的)。 变体 №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;
});

变体 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;
                });
            });
        });
    });
});

请说说这两个函数的缩减有多紧凑?

您可以参考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);
});

这会执行以下操作:

  1. 创建引用两个匹配对象的单个 jQuery 对象。
  2. 为两个对象上的 'change' 事件注册事件处理程序。
  3. 当该事件触发时,它会确保两个对象的 checked 属性 设置为刚刚更改的设置(因此两个对象将相互跟踪)。
  4. 为了简化起见,这只是为两个对象设置 checked 属性,即使不必设置当前对象。您可以使用 .not(this) 过滤掉 this 对象,但实际上没有意义。例如,您可以这样做:

代码:

var matches = jQuery("#matchesWithEmail, #matchesWithEmail-2");
matches.on('change', function(e) {
    matches.not(this).prop("checked", this.checked);
});