为什么这段js脚本不能够给出alert提醒?


rt,写了一段js脚本,目的是获取用户输入的表单的内容并且通过alert()函数返回以确认信息
先贴html:


 <a href="../index.html"><input type='button' value="SUBMIT" name="submit" id="submit" class="apply" onClick="getInfo()" /></a>

然后js脚本:


 // JavaScript Document
function getInfo()
{
    var username,office,phone,food,amount,cost;

    username = document.getElementById("username").value;
    office = document.getElementById("office").value;
    phone = document.getElementById("phone").value;
    food = document.getElementById("food").value;
    amount = parseInt(document.getElementById("amount").value);


    switch(food){
        case "Sizzling Fry Jacks":
            cost = 100;break;
        case "Earthy Johnny Cake":
            cost = 70;break;
        case "Cut-o-Brute":
            cost = 50;break;
        case "Berlize Traditional Beer":
            cost = 30;break;
    }
    cost *= amount;


    alert("Username: "+username+"\n"+"Office: "+office+"\n"+"Phone: "+phone+"\n"+"Food: "+food+"\n"+"Amount: "+amount+"\n"+"Total cost: "+cost+"<br /"+"Your food will arrive in 10 minutes!");
}

p.s.:food表单是一个下拉列表,其他都是文本框或者number框

问题出在:js脚本只有正常运行到变量声明部分。再往后面都不能正常运行,alert()函数也不能执行,不能给出提醒,但是也没找到错误。。。

谢谢!

前端 HTML JavaScript

扌空萝莉D宅 9 years, 4 months ago

我自己按照楼主写的样子写了个表单,js和按钮用的都是题主的,我能正常运行。楼主不妨贴下表单那部分看看

jesten answered 9 years, 4 months ago

莫名其妙解决了。。。。什么都没改,结果过了会突然就好了。。。估计是因为浏览器的原因(卡了之类的?)。。。总之还是谢谢回答的人了!

花开院.柚罗 answered 9 years, 4 months ago

case 里面不能是字符串的啊
先用 if 做判断,再赋数值 进 switch 就好了

dg34513 answered 9 years, 4 months ago

这种问题打断点解决比较好

妮可喵帕斯 answered 9 years, 4 months ago

我估计你的form表单是如下这样的吧:


 html


 <form>
        <input type="text" id="username" placeholder="username"/>
        <input type="text" id="office" placeholder="office"/>
        <input type="text" id="phone" placeholder="phone"/>
        <select id="food">
            <option value="Sizzling Fry Jacks">Sizzling Fry Jacks</option>
            <option value="Earthy Johnny Cake">Earthy Johnny Cake</option>
            <option value="Cut-o-Brute">Cut-o-Brute</option>
            <option value="Berlize Traditional Beer">Berlize Traditional Beer</option>
        </select>
        <input type="number" id="amount" placeholder="amount"/>
        <a href="../index.html"><input type='button' value="SUBMIT" name="submit" id="submit" class="apply" onClick="getInfo()" /></a>
    </form>

我用你的js代码测试了一下,是可以使用的。
我感觉将表单的提交按钮嵌入 a 标签里不是一个很好的做法,不知道楼主这样做的目的是什么耶。

炎髮灼眼討伐者 answered 9 years, 4 months ago

Your Answer