如何更多加载按钮

时间:2014-01-31 17:33:54

标签: javascript php html

我醒来创建一个按钮..每次用户点击加载更多buttom我希望它保持数字是这样等等..但到目前为止它得到了十我不知道怎么样每次用户点击按钮时,无需停止即可加载更多内容 继承了我到目前为止的代码

<!DOCTYPE html>
<html>
    <body>

        <p>Click the button to loop through a block of code five times.</p>
        <button onclick="myFunction()">Load More</button>
        <p id="demo"></p>
        <script>
            function myFunction() {
                var y="";
                for (var i=0;i<10;i++) {
                    y=y + "The number is " + i + "<br>";
                }
                document.getElementById("demo").innerHTML=y;
            }
            var x="";
            for (var i=0;i<5;i++) {
                x=x + "The number is " + i + "<br>";
            }
            document.getElementById("demo").innerHTML=x;
        </script>

    </body>
</html>

2 个答案:

答案 0 :(得分:1)

在您发布的代码中,x和y只存在于函数myFunction中,如果你想保持x和y的状态,你需要将x和y的声明移到函数之外,就像这样

...
<script>
// declare x and y outside of myFunction
// this makes them javascript globals (which is considered bad practice tough)
var x = "";
var y = "";

function myFunction()
{
  for (var i=0;i<10;i++)
  // ...
  // do your stuff with x and y
}
</script>

答案 1 :(得分:0)

您需要在函数之外声明计数器变量才能使其正常工作。试试这个:JSFiddle

<script type="text/javascript">
    var i = 0;
    function myFunction() {
        var y="";
        for (var j = 0;j < 5;j++)
        {
            y=y + "The number is " + i + "<br>";
            i++;
        }
        var inner = document.getElementById("demo").innerHTML;
        document.getElementById("demo").innerHTML=inner + y;
    }

    var x="";
    for (;i<5;i++)
    {
        x=x + "The number is " + i + "<br>";
    }
    document.getElementById("demo").innerHTML=x;
</script>