【问题标题】:Getting NaN error出现 NaN 错误
【发布时间】:2013-06-22 17:57:45
【问题描述】:

我正在使用 jQuery .data 来存储元素的点击次数。我可以很好地添加值,但减去会产生 NaN 错误。价值只会增加。我该如何解决这个问题?

HTML:

<div data-click="0">Click here</div>

JS:

$("div").on("click", function(){
    console.log('Current: '+$(this).data('click'))
    $(this).data('click',$(this).data('click')+1);
    setTimeout(function(){
        $(this).data('click',$(this).data('click')-1);
        console.log('After: '+$(this).data('click'))
    },1000);        
});

小提琴:http://jsfiddle.net/bhmC9/

【问题讨论】:

  • NaN 不是错误,您至少可以告诉我们您正在使用的线路。
  • 我很容易明白他在说什么......

标签: javascript jquery nan


【解决方案1】:

当在 setTimeout 回调中时,this 没有您期望的值。以这种方式保存它:

var that = this;
setTimeout(function(){
    $(that).data('click',$(that).data('click')-1);
    console.log('After: '+$(that).data('click'))
},1000);

事实上,$(this) 在那个 sn-p 中出现了很多次,所以缓存它听起来是个好主意。此外,它还无需查看this 是什么:

var $this = $(this);
console.log('Current: '+$this.data('click'))
$this.data('click',$this.data('click')+1);
setTimeout(function(){
    $this.data('click',$this.data('click')-1);
    console.log('After: '+$this.data('click'))
},1000);

【讨论】:

    【解决方案2】:

    你也可以像这样在函数中设置this的范围(通过调用bind):

    $("div").on("click", function(){
        console.log('Current: '+$(this).data('click'))
        $(this).data('click',$(this).data('click')+1);
        setTimeout(function(){
            $(this).data('click',$(this).data('click')-1);
            console.log('After: '+$(this).data('click'))
        }.bind(this),1000);        
    });
    

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 1970-01-01
      • 2017-02-06
      • 2018-09-06
      • 2015-04-06
      • 2018-10-12
      • 2013-06-15
      • 2017-06-23
      • 1970-01-01
      相关资源
      最近更新 更多