I got a variable called "nthchild" var nthchild = ($(ui.selected).index() + 1);
This gives me the nth-child of a list item with the class selected. I even log it in the console and it works fine. However when I try to use this variable but it doesn't work.
我得到一个名为“nthchild”的变量var nthchild = ($(ui.selected).index() + 1);这就给了我一个列表项的第n个子元素。我甚至在控制台登录它,它运行得很好。但是当我尝试使用这个变量时,它不起作用。
$("section:nth-child(" + nthchild + ")").style.marginTop = "200px";
So it should give the section a margin-top of 200px. But the console is giving me the error
所以这部分应该是200px的边距。但是控制台给了我错误。
Uncaught ReferenceError: nthchild is not defined
未捕获的ReferenceError: nthchild未定义
You can find my code on this 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";
1 个解决方案
#1
3
The issue is because you define nthchild
out of scope of the location you attempt to use it. To fix this place the :nth-child
selector within the selected
callback so that it's executed when the selectable
is updated.
问题在于,您在试图使用nthchild的位置范围之外定义了nthchild。要修复此问题,请将:nth-child选择器放在所选回调中,以便在更新可选回调时执行。
Also note that .style.marginTop
is a property of a native Element which is not available on a jQuery object. Instead, use the css()
method, or better yet, put the style in a rule in an external stylesheet and use addClass()
. Try this:
还要注意,.style。marginTop是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');
}
});
});
#1
3
The issue is because you define nthchild
out of scope of the location you attempt to use it. To fix this place the :nth-child
selector within the selected
callback so that it's executed when the selectable
is updated.
问题在于,您在试图使用nthchild的位置范围之外定义了nthchild。要修复此问题,请将:nth-child选择器放在所选回调中,以便在更新可选回调时执行。
Also note that .style.marginTop
is a property of a native Element which is not available on a jQuery object. Instead, use the css()
method, or better yet, put the style in a rule in an external stylesheet and use addClass()
. Try this:
还要注意,.style。marginTop是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');
}
});
});