jQuery - if (this.checked) с несколькими группами ввода - PullRequest
1 голос
/ 13 января 2020

Я пытаюсь запустить функцию на input для каждой группы .tagboxes, но код работает только так, как задумано, для второй группы и не выполняется должным образом для первой. Это проблема с оператором if, септически

if (this.checked) {
   $input.not(this).trigger("change");
}

Или есть проблема с настройкой each?

$(document).ready(function() {
  function darkness(color) {
    color.replace(/^\D+|\)/g, "").trim();
    //console.log(color);
    var rgb = color.split(",");
    //console.log(rgb);
    var final =
      parseInt(rgb[0], 10) + parseInt(rgb[1], 10) + parseInt(rgb[2], 10);
    //console.log(final);
    if (final < 384) {
      return false;
    }
    return true;
  }
  $(".tagboxes").each(function() {
    $group = $(this);
    $input = $group.find("input");
    $input.change(
      (function($group) {
        return function() {
          var label = $(this).next("label");
          var tagbox = $(this).closest(".tagbox");
          var color = label.data("rgb");
          var rgb = `rgb(${color})`;
          var contrast = darkness(color) ? "#202124" : "#fdfdfd";

          if (this.checked) {
            $input.not(this).trigger("change");
            tagbox.css({
              "background-color": rgb,
              color: contrast,
              "border-color": rgb,
              color: contrast
            });
          } else {
            tagbox.css({
              "background-color": "#fff",
              color: "",
              "border-color": ""
            });
          }
        };
      })($group)
    );
  });
  $(function() {
    $("#m_clear").on("click", function() {
      $("input:checked").each(function() {
        $(this).prop("checked", false);
        $(this).trigger("change");
      });
    });
  });
});
.tagboxes {
  display: flex
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="m_clear">Clear All</button>

<div class="tagboxes">

  <div class="tagbox">
    <input id="i0" type="radio" name="radio">
    <label data-rgb="255,64,129" for="i0">
    <b class='text--tagbox'>Lobster</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="i1" type="radio" name="radio">
    <label data-rgb="49,231,182" for="i1">
    <b class='text--tagbox'>Tuna</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="i2" type="radio" name="radio">
    <label data-rgb="0,0,255" for="i2">
    <b class='text--tagbox'>Pine</b>
  </label>
  </div>

</div>

<div class="tagboxes">

  <div class="tagbox">
    <input id="x0" type="radio" name="radio2">
    <label data-rgb="255,64,129" for="x0">
    <b class='text--tagbox'>Lobster</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="x1" type="radio" name="radio2">
    <label data-rgb="49,231,182" for="x1">
    <b class='text--tagbox'>Tuna</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="x2" type="radio" name="radio2">
    <label data-rgb="0,0,255" for="x2">
    <b class='text--tagbox'>Pine</b>
  </label>
  </div>
</div>

Ответы [ 2 ]

3 голосов
/ 13 января 2020

Я редактировал где-то в вашем коде. Вам не нужно использовать IIFE внутри события change. Что касается проблемы с цветом фона, вы можете сбросить весь фон на значение по умолчанию, тогда вам просто нужно применить новый фон для текущего элемента, который содержит входные данные.

$(this).closest('.tagboxes').find('input').each(function() {
    $(this).closest(".tagbox").css({
        "background-color": "#fff",
        color: "",
        "border-color": ""
    });
});

if (this.checked) {
    tagbox.css({
        "background-color": rgb,
        color: contrast,
        "border-color": rgb,
        color: contrast
    });
}

$(document).ready(function() {
    function darkness(color) {
        color.replace(/^\D+|\)/g, "").trim();
        //console.log(color);
        var rgb = color.split(",");
        //console.log(rgb);
        var final =
            parseInt(rgb[0], 10) + parseInt(rgb[1], 10) + parseInt(rgb[2], 10);
        //console.log(final);
        if (final < 384) {
            return false;
        }
        return true;
    }
    $(".tagboxes").each(function() {
        $group = $(this);
        $input = $group.find("input");
        $input.change(function() {
            var label = $(this).next("label");
            var tagbox = $(this).closest(".tagbox");
            var color = label.data("rgb");
            var rgb = `rgb(${color})`;
            var contrast = darkness(color) ? "#202124" : "#fdfdfd";

            $(this).closest('.tagboxes').find('input').each(function() {
                $(this).closest(".tagbox").css({
                    "background-color": "#fff",
                    color: "",
                    "border-color": ""
                });
            });

            if (this.checked) {
                tagbox.css({
                    "background-color": rgb,
                    color: contrast,
                    "border-color": rgb,
                    color: contrast
                });
            }
        });
    });
    $(function() {
        $("#m_clear").on("click", function() {
            $("input:checked").each(function() {
                $(this).prop("checked", false);
                $(this).trigger("change");
            });
        });
    });
});
.tagboxes {
  display: flex
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="m_clear">Clear All</button>

<div class="tagboxes">

  <div class="tagbox">
    <input id="i0" type="radio" name="radio">
    <label data-rgb="255,64,129" for="i0">
    <b class='text--tagbox'>Lobster</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="i1" type="radio" name="radio">
    <label data-rgb="49,231,182" for="i1">
    <b class='text--tagbox'>Tuna</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="i2" type="radio" name="radio">
    <label data-rgb="0,0,255" for="i2">
    <b class='text--tagbox'>Pine</b>
  </label>
  </div>

</div>

<div class="tagboxes">

  <div class="tagbox">
    <input id="x0" type="radio" name="radio2">
    <label data-rgb="255,64,129" for="x0">
    <b class='text--tagbox'>Lobster</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="x1" type="radio" name="radio2">
    <label data-rgb="49,231,182" for="x1">
    <b class='text--tagbox'>Tuna</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="x2" type="radio" name="radio2">
    <label data-rgb="0,0,255" for="x2">
    <b class='text--tagbox'>Pine</b>
  </label>
  </div>
</div>
1 голос
/ 13 января 2020

Необходимо установить область видимости переменных от глобальной до области видимости функции, используя var перед такой переменной, как var $group = и var $input =. В противном случае будет использоваться глобальная переменная, которая будет иметь в качестве значения вторую строку.

$(document).ready(function() {
  function darkness(color) {
    color.replace(/^\D+|\)/g, "").trim();
    //console.log(color);
    var rgb = color.split(",");
    //console.log(rgb);
    var final =
      parseInt(rgb[0], 10) + parseInt(rgb[1], 10) + parseInt(rgb[2], 10);
    //console.log(final);
    if (final < 384) {
      return false;
    }
    return true;
  }
  $(".tagboxes").each(function() {
    var $group = $(this);
    var $input = $group.find("input");
    $input.change(
      (function($group) {
        return function() {
          var label = $(this).next("label");
          var tagbox = $(this).closest(".tagbox");
          var color = label.data("rgb");
          var rgb = `rgb(${color})`;
          var contrast = darkness(color) ? "#202124" : "#fdfdfd";

          if (this.checked) {
            $input.not(this).trigger("change");
            tagbox.css({
              "background-color": rgb,
              color: contrast,
              "border-color": rgb,
              color: contrast
            });
          } else {
            tagbox.css({
              "background-color": "#fff",
              color: "",
              "border-color": ""
            });
          }
        };
      })($group)
    );
  });
  $(function() {
    $("#m_clear").on("click", function() {
      $("input:checked").each(function() {
        $(this).prop("checked", false);
        $(this).trigger("change");
      });
    });
  });
});
.tagboxes {
  display: flex
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="m_clear">Clear All</button>

<div class="tagboxes">

  <div class="tagbox">
    <input id="i0" type="radio" name="radio">
    <label data-rgb="255,64,129" for="i0">
    <b class='text--tagbox'>Lobster</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="i1" type="radio" name="radio">
    <label data-rgb="49,231,182" for="i1">
    <b class='text--tagbox'>Tuna</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="i2" type="radio" name="radio">
    <label data-rgb="0,0,255" for="i2">
    <b class='text--tagbox'>Pine</b>
  </label>
  </div>

</div>

<div class="tagboxes">

  <div class="tagbox">
    <input id="x0" type="radio" name="radio2">
    <label data-rgb="255,64,129" for="x0">
    <b class='text--tagbox'>Lobster</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="x1" type="radio" name="radio2">
    <label data-rgb="49,231,182" for="x1">
    <b class='text--tagbox'>Tuna</b>
  </label>
  </div>

  <div class="tagbox">
    <input id="x2" type="radio" name="radio2">
    <label data-rgb="0,0,255" for="x2">
    <b class='text--tagbox'>Pine</b>
  </label>
  </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...