【问题标题】:Nan error in Safari while using time update script使用时间更新脚本时 Safari 出现 Nan 错误
【发布时间】:2012-09-19 00:12:53
【问题描述】:

我试图使用here 发布的发布时间更新脚本。它工作得很好,除了在 Mobile Safari 上它会产生 NAN 错误。我试图打印出每个变量以查看 NAN 的来源,但没有骰子。如果有人可以帮助我找出错误是在哪里产生的,我应该能够找到解决办法。或者甚至帮助我弄清楚如何最好地找到错误的来源。实际代码如下。

<script src="js/jquery-1.6.3.min.js"></script>
<script>
$(document).ready(function(){   
$.fn.UpdateSince = function(interval) {

var times = this.map(function(){ return { e: $(this), t: parseInt($(this).html()) }; });
var format = function(t) {
    if (t > 60) {
        return Math.floor(t / 60) + ' minutes ago'
    } else {
        return t + ' seconds ago';
    }
}

var update = function(){
    var now = new Date().getTime();
    $.each(times, function(i, o){
        o.e.html(format(Math.round((now - o.t) / 1000)));
    });
};            
window.setInterval(update, interval);
update();

return this;
}
}); 
</script>
<script>
$(document).ready(function(){   
$('.TimeSince').UpdateSince(1000);
}); 
</script>   

编辑:Mobile Safari 调试控制台未显示错误,但所有输出整数均为 NaN。

【问题讨论】:

    标签: javascript mobile-safari nan


    【解决方案1】:

    我猜它就在这里:

    var times = this.map(function(){ return { e: $(this), t: parseInt($(this).html()) }; });
    

    如果$(this).html() 为空,则会失败。

    【讨论】:

    • 我正在缩小范围。让我们看看我是否可以重做它。如果是这样,我会发布我的解决方案。
    • 你可以用这个来防止它:parseInt("0"+$(this).html(),10)
    • 您希望它按预期工作还是仅仅抑制 NaN 错误?我试过了,得到了一些时髦的结果。多修修补补.... html() 之后的 10 有什么需要,?
    • 我们添加零以确保在 HTML 为空白时有一个值。如果您有一个以零开头的字符串,则 parseInt() 假定您使用的是 OCTAL。 ",10" 强制它使用十进制模式。
    • 在 IE、Firefox、Chrome 中运行良好。在 Mobile Safari 中,它的行为就好像它得到的值为 0,即,它没有得到正确的值,但至少它没有在任何地方打印出 NaN。这是预期的还是上面的代码应该得到正确的值?
    猜你喜欢
    • 2015-05-03
    • 2017-02-06
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多