请问这里哪里错了??我按了=按钮无法输出结果。。。

来源:6-11 编程练习

Amaranta

2017-01-29 17:10

       var x = getElementById("txt1").value;

       var y = getElementById("txt2").value;

       var option = getElementById("select").value;

       var result;

       function getResult(){

           if(option=='+'){

               result= x+y;

           }else if(option=='-'){

               result= x-y;

           }else if(option=='*'){

               result= x*y;

           }else{

               result= x/y;

           }

           document.getElementById("fruit").value=result;


写回答 关注

3回答

  • cain_huang
    2017-01-29 20:24:00
    已采纳

    在这里添加 onclick="getResult()" :

    <input type='button' value=' = ' onclick="count()"/> <!--通过 = 按钮来调用创建的函数,得到结果--> 

    然后还有就是,+号问题,由于JS默认取出来的值不确定是否字符串,当使用+号时,需要将其转成数字,result = Number(x) + Number(y); 这样才能得到正确的结果。

  • 慕少1329861
    2022-06-12 21:34:06

    不好意思啊,不能“+0”这种写法,这种写法是字符串拼接了,可以用“*1”的方式

    xewxlewktgec

  • qq_Voustesuniqu_0
    2017-02-05 22:20:39

    getElementById('');这个地方应该是单引号‘  ’而不是双引号“  ”

JavaScript进阶篇

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

467393 学习 · 21877 问题

查看课程

相似问题