单击div时尝试增加数字

时间:2015-08-21 22:12:23

标签: javascript html css

我是HTML,CSS和JavaScript以及本网站的新手。我在学校里学习它们。我只是想知道如何使用函数进行数字增量并访问HTML中的函数?例如,我的JS是:

function pagenumber() {
  page = page+1;
}

我试图让函数完成它的HTML是:

<div class="Begin" id="Begin" onclick="showbegin(); pagenumber()">

3 个答案:

答案 0 :(得分:0)

<div class="Begin" id="begin" onclick="showbegin()"> </div>

<script>
   var count= 0;
   function showbegin(){
       count++;
       document.getElementById("begin").innerText= count;
   }
</script>

答案 1 :(得分:0)

jsfiddle

<div class="Begin" id="Begin" onclick="pagenumber()">
    Page Num - Click Me 
</div>

<script>
    /*
      page variable sits on window object and is considered global
      it's scope is accessible from anywhere, so global vars are dangerous
    */ 
    var page = 0;

    function pagenumber() {

        /*
           now inside the function, totClicks has only the function scope
           two ways to increment ++page or page++.
           page++ returns the current page value and then adds one
           ++page adds one first and then returns the new value
           we'll use ++page because it's a new click, so add one and return the new total
        */
        var totClicks = ++page;

        // update div with id = 'Begin'
        document.getElementById("Begin").innerHTML = "YOU CLICKED ME! " + totClicks;
    }

</script>

答案 2 :(得分:0)

这比你被引导相信要简单得多。您只需使用JavaScript increment prefix (++)直接从onclick属性增加变量。

在此示例中,我使用了一个按钮来模拟可点击的元素,并且我已将onclick属性包装在console.log()包装中以显示该数字正在存在增加。这两件事都可以改变。

&#13;
&#13;
var page = 0;
&#13;
<button onclick="console.log(++page)">Increment Page</button>
&#13;
&#13;
&#13;