为了账号安全,请及时绑定邮箱和手机立即绑定

.className 不适用于表单验证

.className 不适用于表单验证

鸿蒙传说 2022-05-26 17:45:45
我在 getWeight.length < 1 和 getHeight.length < 1 上都遇到了 .className 的问题,它没有添加类名 formValidation。任何想法为什么它不起作用?我一直盯着代码很长时间,我似乎无法弄清楚发生了什么!非常感谢JSfunction calculateBMI() {  let getWeight = document.getElementById('weight').value;  let getHeight = document.getElementById('height').value;  let getBMI = (getWeight / (getHeight*getHeight)).toFixed(2);  let displayBMI = document.getElementById('displaybmi');  if (getWeight.length < 1) {     //alert('Please enter your weight');      getWeight.className = 'formValidation';    }  else if (getHeight.length < 1) {     //alert('Please enter your height');     getHeight.className = 'formValidation';    }  else if(getBMI < 18.5) {    displayBMI.className = 'displaybmi green';    displayBMI.textContent = 'You\'re under weight! ' + getBMI;    }    else if (getBMI >= 18.5 && getBMI <= 25) {    displayBMI.className = 'displaybmi green';    displayBMI.textContent = 'You\'re normal weight! ' + getBMI;    }   else if (getBMI > 25 && getBMI <= 29.99) {    displayBMI.className = 'displaybmi yellow';    displayBMI.textContent = 'You\'re over weight! ' + getBMI;    }   else if (getBMI >= 30 && getBMI <= 34.99) {    displayBMI.className = 'displaybmi orange';    displayBMI.textContent = 'You\'re obese! ' + getBMI;    }   else {    displayBMI.className = 'displaybmi red';    displayBMI.textContent = 'You\'re very obese! ' + getBMI;   } }.displaybmi {  font-size: 16px;  padding: 20px;  margin-bottom:20px;}.red{  background:red;}.yellow {  background: yellow;}.green{  background:green;}.orange {  background:orange;}.formValidation {  border: 2px solid red;}
查看完整描述

1 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

您正在尝试将类名添加到元素的值(我想是输入)。


getWeight并且getHeight是值,而不是 DOM 实际元素。


尝试:


let getWeight = document.getElementById('weight');

let getHeight = document.getElementById('height');

let getBMI = (getWeight.value / (getHeight.value*getHeight.value)).toFixed(2);


if (getWeight.value.length < 1) {

    //alert('Please enter your weight');

    getWeight.className = 'formValidation';

}

else if (getHeight.value.length < 1) {

    //alert('Please enter your height');

    getHeight.className = 'formValidation';

}


查看完整回答
反对 回复 2022-05-26
  • 1 回答
  • 0 关注
  • 112 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号