无法使javascript添加运算符正确添加

Cant get javascript addition operator to add correctly

本文关键字:添加 运算符 javascript      更新时间:2023-09-26

我有一个按钮,每次单击它时,我都希望它在数据属性中添加5。出于某种原因,我很难弄清楚这一点。我尝试了几种不同的方法,但似乎都不适合我

var i = 5;
$(this).attr('data-count', ++i);

但由于某种原因,它只触发一次。如果我点击它,它会将数据属性设置为6,但如果我再次点击它,则它将保持在6。

然后我尝试了普通的javascript添加运算符,但它的操作不正确。

var x = 5;
var y = count;
var newcount = x + y;
$(this).attr('data-count', newcount);

这个的输出是50,然后再次点击它是550,依此类推

我确信我错过了什么,但我不确定我做错了什么。

我真的希望第一个例子能起作用,因为我想计数,因为我正在添加到现有的列表中,因为我的完整代码如下。

$( document ).on( "click", "#showButton", function() {
    var q = $(this).attr('data-q');
    var type = $(this).attr('data-type');
    var count = $(this).attr('data-count');
    $(this).text('More');
    var i = 5;
    $(this).attr('data-count', ++i);
    $.ajax({ 
       dataType: 'html',
       data: '',
       type: 'POST',
       url : '',
       success: function(response) {
          $('#responseContainer').append(response);
       }
    });
});

,需要记住的几件事

ajquery标识以data开头的属性,因此为了提取它,您可以简单地使用.data('attr')而不是.attr('data-attr')
b为了增加一个值,您需要将其附加到现有值上,因此您需要:$(this).data('count', $(this).data('count') + (++i));

$( document ).on( "click", "#showButton", function() {
    var count = $(this).data('count');
    $(this).text('More');
    var i = 5;
    $(this).data('count', $(this).data('count') + (++i));
    alert($(this).data('count'));
    });

示例:https://jsfiddle.net/DinoMyte/1e0fvkng/

  1. "问题"
    初始化:$this.data('count', 0)
    onclick:$this=$(this);$this.data('count', $this.data('count')+5)
  2. "问题"
    newcount = x++y

原因是y是一个字符串,当您使用attr而不是data时。。。

提示:您可以使用对象作为数据,例如:
$(this).data('prop', {count:0});$(this).data('prop').count+=5;