【问题标题】:Change background color according to the text contained between the tags根据标签之间包含的文本更改背景颜色
【发布时间】:2022-10-14 22:30:26
【问题描述】:

我需要帮助来开发一个函数来测试两个 div 标签(特定类)之间包含的值是否等于字符串。

然后我需要将它包装在一个循环中,该循环在加载时在我的整个页面上执行此操作。

然后我需要将它添加到每篇文章的循环中。

你知道我该怎么做吗?

function changeBackgroundColor() {
  var text = document.getElementsByClassName("disponibilite_mh")[0].innerText;
  const bg_defaut = document.getElementsByClassName("disponibilite_mh")[0].style.backgroundColor = 'white';
  switch (text) {
    case 'Available':

      document.getElementsByClassName("disponibilite_mh")[0].style.backgroundColor = 'green';

      break;

    case 'Reserved':
      document.getElementsByClassName("disponibilite_mh")[0].style.backgroundColor = 'orange';

      break;

    case 'Selled':
      document.getElementsByClassName("disponibilite_mh")[0].style.backgroundColor = 'red';
      break;
    default:
  }
}
window.onload = changeBackgroundColor;
<div class="disponibilite_mh">Available</div>

【问题讨论】:

  • 您反复查找document.getElementsByClassName("disponibilite_mh"),然后使用第一个。您应该一次找到它们(通过一次调用),然后编写一个循环来分别遍历每个。循环是大多数语言的基本部分,并且有很多关于这个主题的教程
  • 请在此 javascript 中添加您的 HTML,并说明 between two div tags 是指在同一元素的开始和结束标记之间还是在两个单独的 DIV 元素之间
  • 我给你做了一个sn-p。我必须添加一个} 才能使其工作。请编辑它以使其成为minimal reproducible example

标签: javascript html css


【解决方案1】:

这应该可以解决您的问题。

function changeBackgroundColor() {
    const elements = document.getElementsByClassName("disponibilite_mh");
    for (let element of elements) {
        switch (element.innerText) {
            case 'Available':
                element.style.backgroundColor = 'green';
                break;
            case 'Reserved':
                element.style.backgroundColor = 'orange';
                break;
            case 'Selled':
                element.style.backgroundColor = 'red';
                break;
            default:
                element.style.backgroundColor = 'white';
        } 
    }
}
window.onload = changeBackgroundColor;

【讨论】:

  • 这可以是 DRYer。看我的回答
【解决方案2】:

请缓存元素。保持干燥

或者更好的是,循环并仅在开关中设置颜色值:

const changeBackgroundColor = () => {
  document.querySelectorAll(".disponibilite_mh").forEach(disp => {
    const text = disp.innerText.trim();
    switch (text) {
      case 'Available':
        color = 'green';
        break;
      case 'Reserved':
        color = 'orange';
        break;
      case 'Selled':
        color = 'red';
        break;
      default:
        color = 'white'
    }
    console.log(text,color)
    disp.style.backgroundColor = color;
  })
}
window.addEventListener("DOMContentLoaded", changeBackgroundColor);
<div class="disponibilite_mh">Available</div>
<div class="disponibilite_mh">Reserved</div>
<div class="disponibilite_mh">Selled</div>

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 2019-01-08
    • 2018-09-29
    • 2015-12-31
    • 1970-01-01
    • 2016-05-13
    相关资源
    最近更新 更多