简体   繁体   中英

Reference Error: variable is not defined

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.

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

Uncaught ReferenceError: nthchild is not defined

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";

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.

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM