简体   繁体   English

参考错误:未定义变量

[英]Reference Error: variable is not defined

I got a variable called "nthchild" var nthchild = ($(ui.selected).index() + 1); 我得到了一个名为“nthchild”的变量var nthchild = ($(ui.selected).index() + 1); This gives me the nth-child of a list item with the class selected. 这给了我选择类的列表项的第n个子项。 I even log it in the console and it works fine. 我甚至在控制台中记录它,它工作正常。 However when I try to use this variable but it doesn't work. 但是,当我尝试使用此变量但它不起作用。

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

So it should give the section a margin-top of 200px. 所以它应该给该部分一个200px的上限。 But the console is giving me the error 但是控制台给了我错误

Uncaught ReferenceError: nthchild is not defined 未捕获的ReferenceError:未定义nthchild

You can find my code on this codepen 你可以在这个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";

The issue is because you define nthchild out of scope of the location you attempt to use it. 问题是因为您将nthchild定义在您尝试使用它的位置范围之外。 To fix this place the :nth-child selector within the selected callback so that it's executed when the selectable is updated. 要修复此位置:nth-child selected回调中的:nth-child选择器,以便在更新selectable时执行。

Also note that .style.marginTop is a property of a native Element which is not available on a jQuery object. 另请注意, .style.marginTop是本机Element的一个属性,在jQuery对象上不可用。 Instead, use the css() method, or better yet, put the style in a rule in an external stylesheet and use addClass() . 相反,使用css()方法,或者更好的是,将样式放在外部样式表中的规则中并使用addClass() Try this: 试试这个:

$(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