如何使用JavaScript从此html的输入元素中获取值,以及如何更改输入元素的背景

时间:2019-04-04 15:20:01

标签: javascript html arrays

我需要javascript将输入元素的背景更改为红色(如果数字大于前一个数字)或红色(如果小于前一个数字

html中input元素的值应该在数组中,然后javascript应该分析该数组,如果该数字大于前一个数字,则使输入元素背景为绿色,如果小于前一个数字,则为红色

HTML

 <form>
   <input type="number" class="display" value="" id= "seat-1">
   <input type="number" class="display" value="" id= "seat-2">
   <input type="number" class="display" value="" id= "seat-3">
   <input type="number" class="display" value="" id= "seat-4">  
   <input type="number" class="display" value="" id= "seat-5">
   <input type="number" class="display" value="" id= "seat-6">
 </form>

获取值的Javascript

 let seat1 = document.getElementById("seat-1").value;
 let seat2 = document.getElementById("seat-2").value;
 let seat3 = document.getElementById("seat-3").value;
 let seat4 = document.getElementById("seat-4").value;
 let seat5 = document.getElementById("seat-5").value;
 let seat6 = document.getElementById("seat-6").value;

将其制成数组并在输入背景上显示红色或绿色的Javascript

 let seatRow1 = [ seat1,  seat2, seat3, seat4, seat5, seat6];

    for (let i = 0; i <  seatRow1.length;   i++) {

      if ( (seatRow1[i + 1]) > seatRow1[i]) {
       document.getElementByClassName("display").style.backgroundColor = 
          "green";
            }
      else { 
       document.getElementByClassName("display").style.backgroundColor = 
     "red";
     }
     }

谢谢

1 个答案:

答案 0 :(得分:0)

除了获取页面加载时的元素值之外,您还需要在元素值之一发生变化时检查值(因为页面加载时的值可能会随着用户输入信息而发生变化)。一种方法是侦听input事件,然后检查更改后的输入的值并将其与同级进行比较。例如:

const changeBackground = (elem, v1, v2) => {
  if (v1 < v2) {
    elem.style.backgroundColor = 'red';
  } else if (v1 > v2) {
    elem.style.backgroundColor = 'green';
  } else {
    elem.style.backgroundColor = 'transparent';
  }
}

const inputs = document.querySelectorAll('.display');

for (let input of inputs) {
  input.addEventListener('input', (event) => {
    let curr = event.target;
    let prev = curr.previousElementSibling;
    let next = curr.nextElementSibling;
    let cval = parseFloat(curr.value);
    if (prev) {
      changeBackground(curr, cval, parseFloat(prev.value));
    }
    if (next) {
      changeBackground(next, parseFloat(next.value), cval);
    }
  });
}
<form>
  <input type="number" class="display" value="" id="seat-1">
  <input type="number" class="display" value="" id="seat-2">
  <input type="number" class="display" value="" id="seat-3">
  <input type="number" class="display" value="" id="seat-4">
  <input type="number" class="display" value="" id="seat-5">
  <input type="number" class="display" value="" id="seat-6">
</form>