无法从按钮调用JavaScript函数

时间:2018-07-07 15:01:42

标签: javascript html

我正在尝试用多种语言编写臭名昭著的FizzBu​​zz程序,但我迷上了JavaScript。我试图通过按钮调用该函数,但是它不起作用,即使我尝试正常调用该函数,也会发生相同的情况。我尝试了多种不同的输出方法,但没有影响,所以希望有人可以告诉我我做错了什么。这是代码:

<!DOCTYPE html>
<html>
    <body>

        <div class="center">
            <h1>This is FizzBuzz</h1>
            <button onclick="fizzBuzz()">Run FizzBuzz</button> 
            <p id="hi">Hi there</p>
        </div>

        <style>
            .center {
                text-align: center;
                font-family:Arial;
            }
        </style>

        <script> //JavaScript
            var idd = document.getElementById("hi");
            function fizzBuzz(){
                idd.innerHTML = "hi";
                for (x = 0; x = 15; x++) {
                    idd.innerHTML = x;
                    if (x % 3 == 0 && x % 5 == 0){
                        idd.innerHTML = "FizzBuzz";
                    } else if((x % 3)= 0){
                        idd.innerHTML = "Fizz";
                    } else if((x % 5) = 0){
                        idd.innerHTML = "Buzz";
                    } else {
                        idd.innerHTML = x;
                    }
                }
            }
            fizzBuzz();
        </script>
    </body>

</html>

2 个答案:

答案 0 :(得分:1)

INAlternativeAppNames将永远不会为假,这意味着循环将永远持续下去。尝试将其更改为x = 15

x < 15

function fizzBuzz(){ idd.innerHTML = "hi"; for (x = 0; x < 15; x++) { idd.innerHTML = x; if (x % 3 == 0 && x % 5 == 0){ idd.innerHTML = "FizzBuzz"; } else if((x % 3) == 0){ idd.innerHTML = "Fizz"; } else if((x % 5) == 0){ idd.innerHTML = "Buzz"; } else { idd.innerHTML = x; } } } 一样,您还需要使用==而不是=进行比较,以使其工作。

答案 1 :(得分:0)

<!DOCTYPE html>
<html>
    <body>

        <div class="center">
            <h1>This is FizzBuzz</h1>
            <button onclick="fizzBuzz()">Run FizzBuzz</button> 
            <p id="hi">Hi there</p>
        </div>

        <style>
            .center {
                text-align: center;
                font-family:Arial;
            }
        </style>

        <script> //JavaScript
            var idd = document.getElementById("hi");
            function fizzBuzz(){
                idd.innerHTML = "hi";
                for (x = 0; x < 15; x++) {
                    idd.innerHTML = x;
                    if (x % 3 == 0 && x % 5 == 0){
                        idd.innerHTML = "FizzBuzz";
                    } else if((x % 3)== 0){<!--here '=='-->
                        idd.innerHTML = "Fizz";
                    } else if((x % 5) == 0){<!--here '=='-->
                        idd.innerHTML = "Buzz";
                    } else {
                        idd.innerHTML = x;
                    }
                }
            }
            fizzBuzz();
        </script>
    </body>

</html>