2017-02-17 111 views
4

我得到了一个名为“nthchild”的变量var nthchild = ($(ui.selected).index() + 1); 这给了我一个列表项的第n个孩子与所选择的类。我什至登录到控制台,它工作正常。但是,当我尝试使用此变量,但它不起作用。参考错误:变量未定义

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

因此,它应该给该部分200px的margin-top。但控制台是给我的错误

Uncaught ReferenceError: nthchild is not defined

你可以找到我的代码对这个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"; 

回答

3

的问题是因为你定义nthchild出你尝试使用它的位置的范围。为了修复这个地方,selected回调中的:nth-child选择器,以便在selectable更新时执行。

另请注意,.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'); 
     } 
    }); 
}); 
+0

不应该是$(“section:nth-​​child(”+ nthchild +“)”)。css({'margin-top':'200px'});或document.getElementsByTagName(“section”)[nthchild] .style.marginTop =“200px”; – PersyJack

+0

@PersyJack你是对的,谢谢。我错过了那部分 –

+0

对。这很好用!但现在divs不会回到他们原来的位置,当我取消选择它们时:/ –