[英]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.