1

我正在尝试增加按钮点击的值。如果只有 1 个按钮,这很容易,但如果有多个按钮,我对如何跟踪计数感到困惑。这似乎更具挑战性,因为在页面加载之前我不知道我必须跟踪多少按钮计数。最终目标是在单个页面上构建多个 AJAX 分页方案(从我的数据库中按顺序加载较旧的列表项,并且特定于单击的项)。

这是我开始了解的 JSFiddle(下面是它的 JS 和 HTML):http: //jsfiddle.net/trpeters1/menAX/6/

JS:

var cnt=function(id){ //this code is incomplete but hopefully you'll get the idea of what i'm trying to do...
var j=0;
for(var i=0; i>100; i++){
    if(id[i]==i) j+=5;
}
    return j;
};

$('button').click(function(){  
   var id=this.id;
   var c=cnt(id); //something which will return the current increment value of the button that was clicked 
   $('#'+id+'div').append(c+'message'+id+'<br>');
});​

HTML:

<button type="button" id="btn1">1</button><div id="btn1div"></div>
<button type="button" id="btn2">2</button><div id="btn2div"></div>
<button type="button" id="btn3">3</button><div id="btn3div"></div>  

此代码的问题是单击每个按钮都会输出相同的消息。理想情况下,代码将能够跟踪每个被点击的按钮。我认为这可行的方式是将每个按钮id与它自己的计数器联系起来(可能需要多个j计数器?)。

想法?

4

3 回答 3

3

您可以使用 jQuery 的.data()方法为每个按钮存储一个计数器:

$('button').click(function(){

    var $this = $(this),
        c = $this.data('count'); // get count for current button
    if (!c) c = 0;               // if not defined yet set to 0
    c++;                         // increment count
    $this.data('count',c);       // save updated count

    // Do something with c here
});

演示:http: //jsfiddle.net/menAX/8/

于 2012-10-26T01:25:25.067 回答
1

对于可能碰巧有同样问题的人在这里重复,这就是我解决问题的方法。它依赖于使用匿名对象,它在 Javascript 中的工作方式类似于字典/地图/哈希表。第一次按下按钮时,该属性不存在,因此将其初始化为 1,然后递增。

这对我有用

<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
var counter = {};
$(function() {

    $('button').click(function(){  
        var id=this.id;
        if (counter.hasOwnProperty(id)) {
            counter[id] += 1;
        } else {
            counter[id] = 1;
        }
        var c= counter[id];
        $('#'+id+'div').append(c+' message '+id+'<br>');
    });
});
</script>
</head>
<body>
<button type="button" id="btn1">1</button><div id="btn1div"></div>
<button type="button" id="btn2">2</button><div id="btn2div"></div>
<button type="button" id="btn3">3</button><div id="btn3div"></div>
</body>
</html>
于 2012-10-26T01:40:45.107 回答
1

像这样的东西?

$('button').click(function() {
    var $elem = $('#'+ this.id +'div');
    var c = $elem.children().length;
    $elem.append(c + 'message' + id + '<br>');
});

http://jsfiddle.net/hZHW3/

于 2012-10-26T00:56:41.897 回答