我想做的是创建一个变量,它是一个特定的类/id 对象。 例如,在第 (5) 和 (8) 行中,我对 ID shoe-carousel 进行了字面引用,我想要一个表示 shoe-carousel 的变量。 问题是如果我做类似的事情:
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 所指出的,实际上它没有任何区别。
关于javascript - 我应该如何初始化这个变量以便与 jQuery 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35615589/