【问题标题】:Changing background color input when contain word包含单词时更改背景颜色输入
【发布时间】:2019-05-22 17:20:21
【问题描述】:

您好,我有如下代码,当我输入单词“BH”或“bh”时,我的背景颜色将变为黄色。如何更改 javascript 代码以检测长文本中包含的单词? 例如,当我将“Somethink text BH in input”之类的文本放在黄色背景上时,我想在长文本中检测像 BH 这样的单个字母

function checkFilled() {
	var inputVal = document.getElementById("subEmail");
    if (inputVal.value == "BH" || inputVal.value == "bh") {
        inputVal.style.backgroundColor = "yellow";
    }
    else{
        inputVal.style.backgroundColor = "";
    }
}
 
checkFilled();
<input type="text" id="subEmail" onchange="checkFilled();"/>

【问题讨论】:

  • 检查.includes的值是否是你要找的子串?
  • 是的,它在我的代码中会怎样?
  • @CertainPerformance includes 在 IE developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 中不受支持
  • @Smollet777 最好不要为了过时的浏览器而削弱编写简短、易于理解的代码的能力——这就是 polyfill 和 Babel 的用途

标签: javascript html


【解决方案1】:

你可以使用.match:

function checkFilled() {
  var inputVal = document.getElementById("subEmail");
  if (inputVal.value.match("bh|BH")) {
    inputVal.style.backgroundColor = "yellow";
  }
  else{
    inputVal.style.backgroundColor = "";
  }
}

checkFilled();

【讨论】:

  • 这就是我要找的!谢谢,我可以更改此代码并与 CSS 连接,通过 CSS 代码更改颜色,而不是像现在这样直接在 js 中)?
  • @Joe 动态更改 css 的唯一方法是通过 javascript。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-07
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
  • 2014-06-12
  • 2020-04-17
相关资源
最近更新 更多