最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript hit counter - Stack Overflow

programmeradmin1浏览0评论

I have just started learning Javascript, and I attempted to write code for hit counter for a webpage using Javascript. I know that we have to use cookies to get the correct number and use PHP to modify data stored in servers. But could you please debug this for me ? I'm getting the output as "The number of visitors is: NaN"

This is my code:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div>
    <p>The number of visitors is : <span id="cntr">0</span></p>
  </div>

  <script>
    function counter_fn() {
      var counter = document.getElementById("cntr");
      var count = 0;
      count = counter.value;
      count = count + 1;
      counter.innerHTML = count;
    }
    window.onload = counter_fn;
  </script>
</body>

</html>

I have just started learning Javascript, and I attempted to write code for hit counter for a webpage using Javascript. I know that we have to use cookies to get the correct number and use PHP to modify data stored in servers. But could you please debug this for me ? I'm getting the output as "The number of visitors is: NaN"

This is my code:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div>
    <p>The number of visitors is : <span id="cntr">0</span></p>
  </div>

  <script>
    function counter_fn() {
      var counter = document.getElementById("cntr");
      var count = 0;
      count = counter.value;
      count = count + 1;
      counter.innerHTML = count;
    }
    window.onload = counter_fn;
  </script>
</body>

</html>

Share Improve this question edited Aug 13, 2017 at 6:05 Anurag Singh Bisht 2,7534 gold badges21 silver badges27 bronze badges asked Aug 13, 2017 at 4:40 jmdonsjmdons 11 gold badge1 silver badge3 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 2

You are trying to get the valuefrom a span element, which is wrong. Your counter.value is undefined so it will give you the wrong answer.

You can get the 0 from the span by using document.getElementById("cntr").innerHTML. But the value returned is in string. So you need to do parseInt to convert it into integer and only then your addition will give you the correct value.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div>
    <p>The number of visitors is : <span id="cntr">0</span></p>
  </div>

  <script>
    function counter_fn() {
      var counter = document.getElementById("cntr");
      var count = 0;
      count = parseInt(counter.innerHTML);
      count = count + 1;
      counter.innerHTML = count;
    }
    window.onload = counter_fn;
  </script>
</body>

</html>

You need to use parseInt

<script> 
    function counter_fn(){
       var counter = document.getElementById("cntr");
       var count = 0;
       count = parseInt(counter.value);
       count = count+1;
       counter.innerHTML = parseInt(count);
    }
    window.onload = counter_fn;  
 </script>

UPDATE

As @Anurag Singh Bisht mented, you cannot get value from a span element . So to get value from <span> you need to use $('span').text();

<html>
    <body>
        <div id="cntr"> 
            The number of visitors is : 
            <span>0</span>
        </div>

       <script> 
            function counter_fn(){
                var counter = $('#cntr span').text(); // geting value from span
                var count = 0;
                count = parseInt(counter.value);
                count = count+1;
                counter.innerHTML = parseInt(count);
           }
           window.onload = counter_fn;  
      </script>
    </body>
</html>

You need to parse the string to an integer and you need to get the innerHTML.

<script> 
  function counter_fn(){
    var counterElement = document.getElementById("cntr")
    var counterNumber = parseInt(counterElement.innerHTML)
    counterNumber = counterNumber + 1
    counterElement.innerHTML = counterNumber
  }
  window.onload = counter_fn;  
</script>

The correct way to do it would be storing this value somewhere else, like localStorage and reading it from there. You are not supposed to read your own HTML to update the value. HTML elements are supposed to be results, not your input.

var counterNumber = 1

if (localStorage.getItem("count")) {
  counterNumber = parseInt(localStorage.getItem("count")) + 1
}
else {
  localStorage.setItem("count", counterNumber)
}

To fix every refresh showing 1 (refer ment for Eren Tanteken suggestion), we need to add another line as shown below:

var counterNumber = 1

if (localStorage.getItem("count")) {
  counterNumber = parseInt(localStorage.getItem("count")) + 1
  localStorage.setItem("count", counterNumber)
}
else {
  localStorage.setItem("count", counterNumber)
}

This way we will be updating the new value in local storage. Hope this helps

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>