简体   繁体   English

为什么我的Javascript Switch Case无法运作?

[英]Why isn't my Javascript Switch Case working?

When using the JSfiddle interpreter, the button and input field appear in the 'result' box, however there doesn't seem to be any response to the script. 使用JSfiddle解释器时,按钮和输入字段显示在“结果”框中,但是似乎没有对该脚本的任何响应。 I tried other interpreters, such as that of the W3School, and while it does give me an indication that the function is in fact being called, the result seems to only be the default case, and even that only appears for a fraction of a second before the entire field along with the button and input disappear (Worth noting the text I input does not appear in the paragraph, and 'fruitT' seems to be ignored -- so most likely there is an issue with the passing of info between the input field, the button and the function.) 我尝试了其他解释器,例如W3School的解释器,虽然它确实表明确实在调用该函数,但结果似乎只是默认情况,甚至只是一秒钟的时间在整个字段以及按钮和输入消失之前(值得注意的是,我输入的文本没有出现在该段落中,并且'fruitT'似乎被忽略了-因此很可能在输入之间传递信息存在问题字段,按钮和功能。)

The logic seems pretty straightforward to me and I've looked at other examples -- however I am new to JS so I've potentially overlooked some syntax. 逻辑对我来说似乎很简单,我看了其他示例-但是我是JS的新手,所以我可能忽略了某些语法。 Hoping somebody could give me a push in the right direction. 希望有人可以帮助我朝正确的方向前进。 Thanks! 谢谢!

<!DOCTYPE html>
<html>

<body>
    <form action="#">
        <input id="fruit">
            <button onclick="myFunc('fruit')">Enter</button>
    </form>
        <p id="here"></p>

<script>
function myFunc(fruitT){
  switch (fruitT){
   case "Oranges":
       document.getElementById("here").innerHTML = ("Oranges are $0.59 a pound.");
      break;
   case "Apples":
       document.getElementById("here").innerHTML = ("Apples are $0.32 a pound.<br>");
      break;
   default:
      document.getElementById("here").innerHTML = ("Sorry, we are out of " + fruitT + ".<br>");
}
}
</script>

</body>
</html>

A button inside a form submits the form, as it's default type is submit, reloading the page. 表单内的一个按钮提交表单,因为它的默认类型是Submit,重新加载页面。
You probably also want to pass the inputs value to the function, not just the string 'fruit' 您可能还想将输入值传递给函数,而不仅仅是字符串'fruit'

change this line 改变这条线

<button onclick="myFunc('fruit')">Enter</button>

to

<button type="button" onclick="myFunc(document.getElementById('fruit').value)">Enter</button>

FIDDLE 小提琴

<button onclick="myFunc('fruit')">Enter</button>

Passes the string "fruit" to your function, which would then hit default. 将字符串“ fruit”传递给函数,然后将其击中默认值。

<button onclick="myFunc(fruit)">Enter</button>

Would run the function with the variable fruit, if it exists. 如果存在变量,将使用变量fruit运行该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM