按钮点击计数器
Button click counter
我正在尝试创建一个按钮点击计数器,每次下载都会增加。我想在没有数据库的情况下使用它,这是代码:
<?php
$counterFile = 'counter.txt' ;
// jQuery ajax request is sent here
if ( isset($_GET['increase']) )
{
if ( ( $counter = @file_get_contents($counterFile) ) === false ) die('Error : file counter does not exist') ;
file_put_contents($counterFile,++$counter) ;
echo $counter ;
return false ;
}
if ( ! $counter = @file_get_contents($counterFile) )
{
if ( ! $myfile = fopen($counterFile,'w') )
die('Unable to create counter file !!') ;
chmod($counterFile,0644);
file_put_contents($counterFile,0) ;
}
?>
<script type="text/javascript">
jQuery(document).on('click','a#download',function(){
jQuery('div#counter').html('Loading...') ;
var ajax = jQuery.ajax({
method : 'get',
url : '/test.php', // Link to this page
data : { 'increase' : '1' }
}) ;
ajax.done(function(data){
jQuery('div#counter').html(data) ;
}) ;
ajax.fail(function(data){
alert('ajax fail : url of ajax request is not reachable') ;
}) ;
}) ;
</script>
<div id="counter"><?php echo $counter ; ?></div>
<a href="<?php echo get_field("pdf"); ?>" id="download" onclick="window.open(this.href);return false;">Download btn</a>
问题是,当我单击Download btn
时,pdf会打开,但数字会消失,如果我重新加载页面,它总是保持在0
。知道问题在哪里或是什么吗?
重新加载取决于被单击的链接(毕竟它仍然是一个链接,这将重新加载页面)。
要么返回假:
jQuery(document).on('click','a#download',function(){
...
return false;
});
或者使用preventDefault()
阻止默认操作
jQuery(document).on('click','a#download',function(e){
e.preventDefault()
...
});
您当前在同一按钮上同时使用 onclick=
属性和 jQuery 事件处理程序。这不是一个好情况。
最好只对处理程序使用 jQuery,例如
jQuery(document).on('click','a#download',function(e){
e.preventDefault()
window.open(this.href);
... The other code ...
});
,然后从按钮上取下onclick="window.open(this.href);return false;"
。
相关文章:
- 类似按钮增量计数器不工作.PHP,AJAX,MySQL,javascript
- (PHP)克隆按钮上的按钮点击计数器
- 计数器达到零后显示重置按钮
- 将 AJAX 添加到带计数器的轨道 4 喜欢/不喜欢按钮
- 单击按钮时增加计数器值
- 购买按钮点击计数器
- 仅单击按钮即可递增计数器
- 如何创建一个计数器循环,该循环在单击提交按钮时启动,并输出多行单词,每个单词前面都有一个数字
- 按钮计数器的简码
- 单击“HTML 计数器”按钮
- 如何通过单击按钮更新计数器和替换文本
- 简单的两个按钮计数器html jquery javascript
- 隐藏/显示绑定到计数器的按钮
- 按钮点击计数器
- 按钮点击计数器保存编号
- Javascript:点击按钮即可获得更多功能.点击计数器
- ShareThis.com社交媒体按钮点击计数器错误
- 按下按钮时角度+流星计数器增量
- 单击按钮时增加计数器值,然后重复使用该值
- 单击按钮时增加计数器值