我应该如何初始化此变量以与jQuery一起使用?

我想做的是创建一个特定的类/ id对象的变量。 例如,在第(5)和(8)行中,我对ID,鞋子传送带进行了文字参考,我希望有一个代表鞋子转盘的变量。 问题是如果我做了类似的事情:

var fooCarousel = $('.shoe-carousel'); 

它适用于第(5)行,不适用于第(8)行

 1. //initialize the slide in focus and what will be the center slide 2. var slideInFocus = document.createElement('img'); ​3. 4. //set the index of the immediate slide in focus when the page loads 5. slideInFocus.index = $('.shoe-carousel').slick('slickCurrentSlide'); 6. 7. //set the source of the immediate slide in focus when the page loads 8. slideInFocus.src = $('.shoe-carousel .slick-current img').prop('src'); 

对我来说,第8行的问题似乎是从变量定义中推入的单引号(’)破坏了它; 那么,给像我这样的新JS / jQuery人的诀窍是什么? 谢谢!

在第一次意识到我发布了一个不合适的答案之后,然后根据@ Redmega的答案阅读评论,我认为对OP问题的最有效回应是这样的:

 var fooCarousel = $('.shoe-carousel'); 1. //initialize the slide in focus and what will be the center slide 2. var slideInFocus = document.createElement('img'); ​3. 4. //set the index of the immediate slide in focus when the page loads 5. slideInFocus.index = fooCarousel.slick('slickCurrentSlide'); 6. 7. //set the source of the immediate slide in focus when the page loads 8. slideInFocus.src = $('.slick-current img', fooCarousel).prop('src'); 

虽然非常接近$fooCarousel.find('.slick-current img')解决方案,但这种方式可能对性能影响较小。

编辑:实际上它没有任何区别,正如@Redmega指出的那样。

按照您的建议方式进行操作没有问题,问题是我认为您的实施方式是第8行。您打算如何调用它? 像这样的东西会运作良好。 .find()将在您调用它的jquery对象中找到选择器。

 1. var $fooCarousel = $('.shoe-carousel'); 2. var slideInFocus = document.createElement('img'); ​3. 4. //set the index of the immediate slide in focus when the page loads 5. slideInFocus.index = $fooCarousel.slick('slickCurrentSlide'); 6. 7. //set the source of the immediate slide in focus when the page loads 8. slideInFocus.src = $fooCarousel.find('.slick-current img').prop('src'); 

警告 :正如其他人所指出的,这个答案并没有解决OP问题。 我太快读了这个问题,所以下面提出的代码只适用于包含字符串id的fooCarousel

是的,这是你猜对了。
并且使用常规连接很容易解决,如下所示:

 1. //initialize the slide in focus and what will be the center slide 2. var slideInFocus = document.createElement('img'); ​3. 4. //set the index of the immediate slide in focus when the page loads 5. slideInFocus.index = fooCarousel.slick('slickCurrentSlide'); 6. 7. //set the source of the immediate slide in focus when the page loads 8. slideInFocus.src = $(fooCarousel + ' .slick-current img').prop('src');