这个JavaScript代码(函数)有什么问题?

时间:2015-01-28 21:53:27

标签: javascript function return

抱歉很难,但实际上我有2个几乎相同类型的问题......

第一个问题: 为什么我的代码中的最后三个函数不起作用...

<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <script type="text/javascript">
        //Skriver ut en strengen "Bananer og epler er ikke det samme!"
        document.write("Bananas and apples are not the same! ");
        //Variabelnavnet kan kun inneholde bokstaver, tall, og understrek. Variabelnavnet kan ikke begynne med et tall.
        var banana1 = "rotten"; 
        var banana2 = "good";
        document.write("One banana was " + banana1 + " and the other was " + banana2 + ", and they both know the song \"I'm yellow and I hate it\" very well.<br />");
        //En pop-up melding i samarbeid med XHTML.
        function bananas() 
        {alert ("Wow, what a loser u are!");}
        function cherries() 
        {alert ("That's better!");}
        //Flere parametere.
        function pineapples(one, two){
        document.write(one + " are as sweet as " + two + "<br />");
        }
        pineapples("Pineapples", "kiwis");
        pineapples("Watermelons", "citrons");
        pineapples("Dades", "apricots");
        }
        function waterMelons(){
        document.write("I loooove watermelons!");
        }            
        function ciTrons(){
        document.write("But citrons...!");
        }
        function start(){
        waterMelons();
        ciTrons();
        }
        start();
    </script>
    <form>
        <input type="button" value="Click me if u like bananas" onclick="bananas()"/>
        <input type="button" value="Click me if u like cherries" onclick="cherries()"/>
    </form>     
</body>
</html>

但是当我把最后三个函数放在一个单独的文件中时,就像这样......

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
    function waterMelons(){
        document.write("I loooove watermelons!");
        }            
        function ciTrons(){
        document.write(" But citrons...!");
        }
        function start(){
        waterMelons();
        ciTrons();
        }
        start();
</script>       
</body>
</html>

它正在运作!为什么!?

第二个问题

这段代码有问题还是我像烂果子一样愚蠢?为什么不返回值“20”?

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
    <script type="text/javascript">
        function addNumbers(a,b,c){
        var d = a+b+c;
        return d;
        }
        ducument.write(addNumbers(2,6,12));
    </script>
    </body>
</html> 

1 个答案:

答案 0 :(得分:1)

这两个问题都是typos,在第一种情况下你使用了额外的}

    function pineapples(one, two){
      document.write(one + " are as sweet as " + two + "<br />");
    }
      pineapples("Pineapples", "kiwis");
      pineapples("Watermelons", "citrons");
      pineapples("Dades", "apricots");
    } <-- THIS IS WRONG

在第二种情况下,您使用ducument代替document

ducument.write(addNumbers(2,6,12)); <-- MUST BE document

希望这有帮助,