简体   繁体   中英

(Javascript) Script won't count just once, perhaps not recognizing variable?

I'm sure this is a super easy fix and I just can't see it.. I have a play button and I only want it to write to database (inc playcount) only when it's clicked the first time.

Any idea why this doesn't work? This result counts every click, and if I do if countonce = 0 and declare at beginning as 0 it won't count any clicks. Am I misunderstanding javascript?

 <div id="left-05-play_">
 <script type="text/javascript">
 var currsong = 1;
 var playcountadd = document.getElementById('left-05-play_');
 playcountadd.onclick = function() {
 if (countonce != 1) {
 $.post( "php/songadd.php", { addsong: "1", } );
 var countonce = 1;
 } }
 </script>
 </div>

Thank-you for taking the time to read this question.

This should do the trick.

var currsong = 1;
var songadded = false;
var playcountadd = document.getElementById('left-05-play_');

playcountadd.onclick = function() {
   if (!songadded) {
      $.post( "php/songadd.php", { addsong: "1", } );
      songadded = true;
   }
}
  • Changed countonce to songadded
  • Moved songadded out of onclick function
  • Changed songadded to boolean logic
  • Check whether songadded=false before proceeding with AJAX post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM