根据当前文本输入更改 focusout 上单独 div 的背景颜色

Change background color for separate divs on focusout depending on current text input

这个问题已经考虑了好几个小时,但想不出一个解决方案。我有大约 5 div 具有相同的 class:<div contenteditable="true" class="change">

当我点击 div 时,第一个函数将背景色设为白色。 当我离开 div 时,我希望颜色根据我在 div 中写的内容而改变。

好在颜色变了。 糟糕的是,当我随后单击其他 div 并离开它们时,它们会收到与第一个 div 相同的颜色。不管我什么都不写,或者如果我写 "yes"、"no" 或 "maybe",后面的 div 仍然得到与第一个 div 相同的颜色当我离开他们

求助! :(

    $(".change").focus(function() {

    var message = document.querySelector(".change").innerHTML;

        this.style.backgroundColor=("white");

    });



    $((".change") ).focusout(function() {

    var message = document.querySelector(".change").innerHTML;

    console.log(message);

    switch (message) {
      case 'yes':
        this.style.backgroundColor=("green");
        break;
      case 'no':
        this.style.backgroundColor=("red");
        break;
      case 'maybe':
        this.style.backgroundColor=("yellow");
        break;
      default:
        this.style.backgroundColor=("white");
        break;
}
});

只需将 var message = document.querySelector(".change").innerHTML; 更改为 var message = $(this).text ();

$(".change").focus(function() {

var message = document.querySelector(".change").innerHTML;

    this.style.backgroundColor=("white");

});



$((".change") ).focusout(function() {

var message = $(this).text();

switch (message) {
  case 'yes':
    this.style.backgroundColor=("green");
    break;
  case 'no':
    this.style.backgroundColor=("red");
    break;
  case 'maybe':
    this.style.backgroundColor=("yellow");
    break;
  default:
    this.style.backgroundColor=("white");
    break;
    
 }
})
div {
  border: 1px solid black;
}

body {
  background: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div contenteditable="true" class="change"></div>
<br />
<div contenteditable="true" class="change"></div>
<br />
<div contenteditable="true" class="change"></div>
<br />
<div contenteditable="true" class="change"></div>
<br />
<div contenteditable="true" class="change"></div>
<br />

那是因为在您的代码中,您总是引用 document.querySelector(".change").innerHtml

的第一个找到的实例

只需将您的代码更改为:

$(".change").focusout(function(event) {

    var message = event.target.value;

    console.log(message);

    switch (message) {
      case 'yes':
        this.style.backgroundColor=("green");
        break;
      case 'no':
        this.style.backgroundColor=("red");
        break;
      case 'maybe':
        this.style.backgroundColor=("yellow");
        break;
      default:
        this.style.backgroundColor=("white");
        break;
    }
});