2013-06-25 2 views
1

jQuery .data을 사용하여 요소에 대한 클릭 수를 저장합니다. 값을 더할 수는 있지만 빼면 NaN 오류가 발생합니다. 값이 증가합니다. 이 문제를 어떻게 해결할 수 있습니까?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/

+0

'NaN'을 오류가 아니며, 적어도 당신이 그 라인을 알려줄 수 있습니다. – Doorknob

+0

나는 그가 꽤 쉽게 이야기하고있는 것을 알아 냈다 ... –

답변

10

setTimeout 콜백 내부 this 당신이 그것을에 기대하는 값이없는 경우. 이런 식으로 유지 : 그것을 캐싱하는 것은 좋은 생각처럼 들린다

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

, $(this) 그 코드에서 여러번 나타납니다. (bind를 호출하여)

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); 
1

당신은 또한과 같이 함수 내 this의 범위를 설정할 수 있습니다 : 또한, 그것은 또한 this가 무엇인지보고에 대한 필요성을 제거

$("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);   
});