簡體   English   中英

參考錯誤:未定義變量

[英]Reference Error: variable is not defined

我得到了一個名為“nthchild”的變量var nthchild = ($(ui.selected).index() + 1); 這給了我選擇類的列表項的第n個子項。 我甚至在控制台中記錄它,它工作正常。 但是,當我嘗試使用此變量但它不起作用。

$("section:nth-child(" + nthchild + ")").style.marginTop = "200px";

所以它應該給該部分一個200px的上限。 但是控制台給了我錯誤

未捕獲的ReferenceError:未定義nthchild

你可以在這個codepen上找到我的代碼

$(function() {
    $("#selectable").selectable();
});

$(function() {
    $("#selectable").selectable({
        selected: function(event, ui) {
            var nthchild = ($(ui.selected).index() + 1);
            console.log(nthchild);
        }
    });
});

$("section:nth-child(" + nthchild + ")").style.marginTop = "200px";

問題是因為您將nthchild定義在您嘗試使用它的位置范圍之外。 要修復此位置:nth-child selected回調中的:nth-child選擇器,以便在更新selectable時執行。

另請注意, .style.marginTop是本機Element的一個屬性,在jQuery對象上不可用。 相反,使用css()方法,或者更好的是,將樣式放在外部樣式表中的規則中並使用addClass() 試試這個:

$(function() {
    $("#selectable").selectable();

    $("#selectable").selectable({
        selected: function(event, ui) {
            var nthchild = ($(ui.selected).index() + 1);
            $("section:nth-child(" + nthchild + ")").css('marginTop', '200px');
        }
    });
});

暫無
暫無

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

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