addClass(green)仅工作一次

时间:2019-10-30 20:22:05

标签: jquery

当结果数大于10时,我试图使整个div为绿色,否则为红色。当我放置两个使结果小于10的数字时,它是红色,但是当我更改为大于10时,它仍然是红色。绿色仅在刷新页面后输入数字时有效。

$(document).ready(startApp);

function startApp() {
  /*
      add a click handler to the button that calls the function below on click
  */
  function doCalculation() {
    var number1 = Number($('#number1').val());
    var number2 = Number($('#number2').val());
    var result = number1 + number2;
    if (result > 10) {
      $('#display').addClass('highText');
      $('#display span').text(result);
    } else {
      $('#display').addClass('lowText');
      $('#display span').text(result);
    }

  }
  $('#doIt').on('click', doCalculation);

}
/*
    make a function that does the following:
        get the numbers from #number1 and #number2
        add the numbers together
        place the result into the span INSIDE the #display element
        extra:
        if the number > 10, make the entire #display element text green
        otherwise, make it red with the classes above
    
    
    */
.highText {
  color: green;
}

.lowText {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>


<input type="text" id="number1" placeholder="1st number"> +
<input type="text" id="number2" placeholder="2nd number">
<div id="display">result--- <span></span></div>
<button id="doIt">calculate!</button>

1 个答案:

答案 0 :(得分:1)

那是因为您最终都应用了两个类,最后应用了红色类,而否决了绿色类。解?首先使用$('#display').removeClass()删除所有类:

$(document).ready(startApp);

function startApp() {
  /*
      add a click handler to the button that calls the function below on click
  */
  function doCalculation() {
    var number1 = Number($('#number1').val());
    var number2 = Number($('#number2').val());
    $('#display').removeClass();
    var result = number1 + number2;
    if (result > 10) {
      $('#display').addClass('highText');
      $('#display span').text(result);
    } else {
      $('#display').addClass('lowText');
      $('#display span').text(result);
    }

  }
  $('#doIt').on('click', doCalculation);

}
/*
    make a function that does the following:
        get the numbers from #number1 and #number2
        add the numbers together
        place the result into the span INSIDE the #display element
        extra:
        if the number > 10, make the entire #display element text green
        otherwise, make it red with the classes above
    
    
    */
.highText {
  color: green;
}

.lowText {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>


<input type="text" id="number1" placeholder="1st number"> +
<input type="text" id="number2" placeholder="2nd number">
<div id="display">result--- <span></span></div>
<button id="doIt">calculate!</button>