繁体   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