为什么结果是NaN?

来源:6-11 编程练习

imooc客服

2018-08-31 09:03

<!DOCTYPE html><html><head><meta charset="UTF-8" /><title>Document</title><script>window.onload=function(){var oN1=document.getElementById('n1').value;var oN2=document.getElementById('n2').value;var oBtn=document.getElementById('btn');var oResult="";var oObj=document.getElementById('obj').value;switch(oObj){case '+':oResult=parseFloat(n1)+parseFloat(n2);break;case '-':oResult=parseFloat(n1)-parseFloat(n2);break;case '*':oResult=parseFloat(n1)*parseFloat(n2);break;case '/':oResult=parseFloat(n1)/parseFloat(n2);break;}oBtn.onclick=function(){document.getElementById('result').value=oResult;}}</script></head><body><input type="text" id="n1"/><select name="" id="obj" ><option value="+">+</option><option value="-">-</option><option value="*">*</option><option value="/">/</option></select><input type="text" id="n2"/><input type="button" value="=" id="btn"/><input type="text" id="result"/></body></html>

https://img4.mukewang.com/5b8893b8000100a505280300.jpg

https://img2.mukewang.com/5b8893b80001fd3306820775.jpg


写回答 关注

1回答

  • imooc客服
    2018-08-31 09:44:28
    <!DOCTYPE html><html><head><meta charset="UTF-8" /><title>Document</title><script>window.onload=function(){var oBtn=document.getElementById('btn');oBtn.onclick=function toSum(){var oN1=document.getElementById('n1').value;var oN2=document.getElementById('n2').value;var oObj=document.getElementById('obj').value;var oResult='';switch(oObj){case '+':oResult=parseFloat(oN1)+parseFloat(oN2);break;case '-':oResult=parseFloat(oN1)-parseFloat(oN2);break;case '*':oResult=parseFloat(oN1)*parseFloat(oN2);break;case '/':oResult=parseFloat(oN1)/parseFloat(oN2);break;}document.getElementById('result').value=oResult;}}</script></head><body><input type="text" id="n1"/><select name="" id="obj" ><option value="+">+</option><option value="-">-</option><option value="*">*</option><option value="/">/</option></select><input type="text" id="n2"/><input type="button" value="=" id="btn"/><input type="text" id="result"/></body></html>

    关于此题的写法,我把所有人的答案全看了,最后的点击事件全都是写的行内JS代码,没有一个人把整体JS全都写到script中。以下是一种非行间JS的写法。

    https://img4.mukewang.com/5b889d050001aaee06910944.jpg

JavaScript进阶篇

本课程从如何插入JS代码开始,带您进入网页动态交互世界

467364 学习 · 21877 问题

查看课程

相似问题