簡體   English   中英

無法讀取main.js中未定義的屬性“ substr”

[英]Cannot read property 'substr' of undefined in main.js

此代碼:

$(document).ready(function() {                     
$('a').click(function(){
    $('html, body').animate({
            scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top //HERE THE ERROR
    }, 500);
    return false;
}); 
$("#slides").slidesjs({
        width: 940,
        height: 440,
       play: {
                 active: true,
                 auto: true,
                 interval: 9000,
                 swap: true
               }
      });            
});

給我我在標題Uncaught TypeError中寫的錯誤:無法讀取未定義的屬性'substr'

僅當嘗試執行特定操作時才會發生這種情況。 此操作是對來自wordpress插件的照片進行投票:照片競賽wordpress插件。

那么,如果未定義substr(1),該如何停止該行代碼? 我在Google上搜索類似的問題,但沒有任何效果。 如果我評論該行投票照片開始工作,但其他功能停止。

正如評論中指出的那樣,您錯誤地使用了.attr ,但是您也把東西鏈接在一起,以至於當出現問題時,可能不清楚到底是在哪里弄亂了。 這是您的代碼,它會在潛在問題出現時立即進行清理以發出警告(可能有點過頭了,但對學習很有幫助):

$(document).ready(function() {
    $("a").click(function(){
        var $a = $(this),
            href = $a.attr("href");

        if (href && href.length > 1) {
            var sel = '[name="' + href.substr(1) + '"]',
                $el = $(sel);
            if ($el) {
                $("html, body").animate({
                    scrollTop: $el.offset().top
                }, 500);
            } else {
                console.warn("Could not find:", sel);
            }
        } else {
            console.warn("Clicked but no href found");
        }
        return false;
    });

    $("#slides").slidesjs({
        width: 940,
        height: 440,
        play: {
            active: true,
            auto: true,
            interval: 9000,
            swap: true
        }
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM