使用纯Javascript向特定元素添加类

时间:2018-12-17 19:57:07

标签: javascript html arrays svg

我正在评估Svg着色图像。函数通过使用querySelectorAll方法循环遍历并将其转换(以比较其值)为数组,从而根据正确的答案列表评估用户设置的填充色。只有类别为setColor的路径才可以着色。

问题:如何仅将类wrongColor添加到填充颜色错误的路径元素中?

<!--Hypothetical SVG that must be colored correctly.-->
    <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
        <path id="aSVG" class="setColor" d="M10 10 C 20 20, 40 20, 50 10" stroke="black" fill="green" />
        <path id="bSVG" class="setColor" d="M70 10 C 70 20, 120 20, 120 10" stroke="black" fill="red" />
        <path d="M130 10 C 120 20, 180 20, 170 10" stroke="black" fill="white" />
        <path id="cSVG" class="setColor" d="M10 60 C 20 80, 40 80, 50 60" stroke="black" fill="lightblue" />
        <path id="dSVG" class="setColor" d="M70 60 C 70 80, 110 80, 110 60" stroke="black" fill="lightblue" />
        <path d="M130 60 C 120 80, 180 80, 170 60" stroke="black" fill="white" />
        <path id="eSVG" class="setColor" d="M10 110 C 20 140, 40 140, 50 110" stroke="black" fill="lightblue" />
        <path id="fSVG" class="setColor" d="M70 110 C 70 140, 110 140, 110 110" stroke="black" fill="lightblue" />
        <path d="M130 110 C 120 140, 180 140, 170 110" stroke="black" fill="white" />
    </svg>


    <!--Correct answers list. Not visible in user-->
    <ol class="answersList">
        <li class="t1">red</li>
        <li class="t1">green</li>
        <li class="t1">lightblue</li>
        <li class="t1">lightblue</li>
        <li class="t1">lightblue</li>
        <li class="t1">lightblue</li>
    </ol>

下面是一个功能示例,目的是阐明游戏的功能。

@ Amethystx87 您的代码将类wrongColor添加到 all 类别为setColor的路径中。您可以在下面的代码段中看到它。 map属性将创建错误“ document.querySelectorAll(...)。map不是函数”,因为querySelectorAll返回一个Node List(类似数组),因此您必须转换{ {1}}进行数组化,然后可以使用数组方法。

我也遇到了同样的问题,并解决了下面JavaScript代码中的注释“检查用户答案”,“检查正确答案列表”。在注释“ Amethystx87解决方案”中,是我使您的代码可以正常工作的方式,但还没有完全解决。

@DacreDenny 我可能无法利用您的解决方案。我希望下面的代码片段可以使您清楚地了解问题。您会在摘要中看到错误的答案(我故意犯了错误)是前两个(绿色,红色),但正确的(红色,绿色)却出现在答案列表中。

Node List
/*~~~~~~~~check button~~~~~~~~~~~*/

document.querySelector(".check").addEventListener('click', checkSvgAnswers);

function checkSvgAnswers() {


  /*~~~check users answers~~~*/

  var selectedFillColor = document.querySelectorAll(".setColor");
  var selectedFillColorArray = [];
  for (var i = 0; i < selectedFillColor.length; i++) {
    var selectedColors = selectedFillColor[i].getAttribute('fill').toUpperCase();
    selectedFillColorArray.push(selectedColors);
  }

  console.log(selectedFillColorArray);

  /*~~~check correct answers list~~~~~~~~~~~*/

  var correctAnswers = document.querySelectorAll("li.t1");
  var correctAnswersArray = [];
  for (var i = 0; i < correctAnswers.length; i++) {
    var answerList = correctAnswers[i].innerText.toUpperCase();
    correctAnswersArray.push(answerList);
  }

  console.log(correctAnswersArray);

  /*~~~~compare answers helper function~~~~~~~~~~*/
  var isEqual = function(value, other) {

    // Get the value type
    var type = Object.prototype.toString.call(value);

    // If the two objects are not the same type, return false
    if (type !== Object.prototype.toString.call(other)) {
      return false;
    }

    // If items are not an object or array, return false
    if (['[object Array]', '[object Object]'].indexOf(type) < 0) {
      return false;
    }
    // Compare the length of the length of the two items
    var valueLen = type === '[object Array]' ? value.length : Object.keys(value).length;
    var otherLen = type === '[object Array]' ? other.length : Object.keys(other).length;
    if (valueLen !== otherLen) {
      return false;
    }
    // Compare two items
    var compare = function(item1, item2) {

      // Get the object type
      var itemType = Object.prototype.toString.call(item1);

      // If an object or array, compare recursively
      if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
        if (!isEqual(item1, item2)) {
          return false;
        }
      }

      // Otherwise, do a simple comparison
      else {

        // If the two items are not the same type, return false
        if (itemType !== Object.prototype.toString.call(item2)) {
          return false;
        }
        // Else if it's a function, convert to a string and compare
        // Otherwise, just compare
        if (itemType === '[object Function]') {

          if (item1.toString() !== item2.toString()) {

            return false;
          }
        } else if (item1 !== item2) {

          return false;
        }

      }
    };
    // Compare properties
    if (type === '[object Array]') {
      for (var i = 0; i < valueLen; i++) {
        if (compare(value[i], other[i]) === false) {

          return false;
        }
      }
    } else {
      for (var key in value) {
        if (value.hasOwnProperty(key)) {
          if (compare(value[key], other[key]) === false) {

            return false;
          }
        }
      }
    }

    // If nothing failed, return true
    return true;

  };

  /*~~~~~~~~compare colors~~~~~~~~~~~*/
  if (isEqual(selectedFillColorArray, correctAnswersArray)) {
    document.querySelector(".coloringResult").innerHTML = "<span style='color:#00B119;'>&#x2714;</span>";
  } else if (!isEqual(selectedFillColorArray, correctAnswersArray)) {
    document.querySelector(".coloringResult").innerHTML = "<span style='color:#D40D0D;'>&#10007;</span>";
  }
  console.log(isEqual(selectedFillColorArray, correctAnswersArray));

  /*~~~~~~~~Amethystx87 solution*/
  document.querySelectorAll('.setColor').forEach((element) => {
    if (!correctAnswersArray.includes(element.fill)) {
      element.classList.add('wrongColor');
    }
  });
};

2 个答案:

答案 0 :(得分:0)

类似这样的东西

ssh -o StrictHostKeyChecking=no -l $CONST_USERNAME $HOST_NAME_LOGIN "$CONST_FILE -u"

答案 1 :(得分:0)

您可以查询SVG元素,并以与DOM中任何其他元素相同的方式更新SVG元素的类列表。

例如,您可以通过执行以下操作来查询具有fill的“错误填充颜色”的white属性值的所有SVG元素:

const wrongFillColor = "white";

document.querySelectorAll(`svg [fill="${wrongFillColor}"]`)

然后可以迭代结果节点集,并向匹配的元素中添加类,如下所示:

const wrongFillColor = "white";

document.querySelectorAll(`svg [fill="${wrongFillColor}"]`).forEach(function(element) {
  element.classList.add("wrongColor")
})
.wrongColor {
  fill: yellow;
}
<!--Hypothetical SVG that must be colored correctly.-->
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
        <path id="aSVG" class="setColor" d="M10 10 C 20 20, 40 20, 50 10" stroke="black" fill="green" />
        <path id="bSVG" class="setColor" d="M70 10 C 70 20, 120 20, 120 10" stroke="black" fill="red" />
        <path d="M130 10 C 120 20, 180 20, 170 10" stroke="black" fill="white" />
        <path id="cSVG" class="setColor" d="M10 60 C 20 80, 40 80, 50 60" stroke="black" fill="lightblue" />
        <path id="dSVG" class="setColor" d="M70 60 C 70 80, 110 80, 110 60" stroke="black" fill="lightblue" />
        <path d="M130 60 C 120 80, 180 80, 170 60" stroke="black" fill="white" />
        <path id="eSVG" class="setColor" d="M10 110 C 20 140, 40 140, 50 110" stroke="black" fill="lightblue" />
        <path id="fSVG" class="setColor" d="M70 110 C 70 140, 110 140, 110 110" stroke="black" fill="lightblue" />
        <path d="M130 110 C 120 140, 180 140, 170 110" stroke="black" fill="white" />
    </svg>