无法获得javascript函数来执行

时间:2012-01-02 03:21:50

标签: javascript

我是Javascript的初学者,无法获得以下代码。当我点击按钮时,没有任何反应。有人能指出我做错了吗?谢谢!

<html>
<head>
<title>Sarah's Puppy Game</title>
</head>
<body>
    <div id="input">
        <input id="puppyNumber" size=30>
        <button onClick="doLoop()"> Get your puppies </button>
    </div>
    <script type="text/html">
        function doLoop() {
        var number = document.getElementById('puppyNumber').value;
            var puppy = [];
            while (var i = 0; i < parseInt(number); i++) {
                puppy = puppy.push('puppy<br>');
            }
            alert(puppy);


        }
    </script>
</body>
</html>

2 个答案:

答案 0 :(得分:5)

我看到的三个问题。

  1. 首先,对text/javascript

  2. 使用<script type='text/javascript'>
  3. 其次,在循环中将while更改为forwhile循环用于测试条件,但您已设置计数器。

  4. Thrid,请勿使用puppy方法指定push().push()直接作用于数组。

  5. Here's the corrected version in action.

    <!-- type="text/javascript" not "text/html" -->
    <script type="text/javascript">
        function doLoop() {
        var number = document.getElementById('puppyNumber').value;
            var puppy = [];
    
            // This is a for loop, rather than a while loop
            // Also for good measure, use the second param to parseInt() for a
            // decimal radix to avoid getting binary or octal numbers accidentally.
            for (var i = 0; i < parseInt(number, 10); i++) {
                // Don't assign the result back to puppy
                puppy.push('puppy<br>');
            }
            alert(puppy);
    
    
        }
    </script>
    

答案 1 :(得分:1)

而不是......

puppy = puppy.push('puppy<br>');

......只是说...

puppy.push('puppy<br>');

push返回被推送的元素,而不是它被推送到的数组。

您的代码将导致变量puppy设置为字符串"puppy<br>"。然后你会尝试"puppy<br>".push("puppy<br>"),这显然是无效的。