无法读取未定义属性

时间:2015-08-17 14:02:04

标签: javascript jquery

我的病情有问题: Uncaught TypeError: Cannot read property 'length' of undefined 这是逻辑,但我该如何解决这个问题?

谢谢。

<script>
    $(window).scroll(function () {
        var elementms = $("#testms").attr("john");
        if (elementms.length) {

            $({
                someValue: 0
            }).animate({
                someValue: 500
            }, {
                duration: 3000,
                easing: 'swing', // can be anything
                step: function () { // called on every step
                    // Update the element's text with rounded-up value:
                    jQuery('#el').text(commaSeparateNumber(Math.round(this.someValue)));
                }
            });

            function commaSeparateNumber(val) {
                while (/(\d+)(\d{3})/.test(val.toString())) {
                    val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
                }
                return val;
            }
        }
    });    	
</script>

1 个答案:

答案 0 :(得分:0)

或许只是简单检查一下,看看elementms是否足够?

if (typeof elementms !== 'undefined' && elementms.length) {
    …
}

如果elementms现在是undefined,则不会查找属性长度。

我个人更喜欢一种标签较少的解决方案,反之亦然。

$(window).scroll(function () {
    var elementms = $("#testms").attr("john");
    if (typeof elementms === 'undefined' || elementms.length === 0) {
        return;
    }

    $({
        someValue: 0
    }).animate({
        someValue: 500
    }, {
        duration: 3000,
        easing: 'swing', // can be anything
        step: function () { // called on every step
            // Update the element's text with rounded-up value:
            jQuery('#el').text(commaSeparateNumber(Math.round(this.someValue)));
        }
    });
});

function commaSeparateNumber(val) {
    while (/(\d+)(\d{3})/.test(val.toString())) {
        val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }
    return val;
}