javascript - 我应该如何初始化这个变量以便与 jQuery 一起使用?

标签 javascript jquery

我想做的是创建一个变量,它是一个特定的类/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/

相关文章:

javascript - 初学者 Javascript 和 DOM 应该先学什么?

javascript - 从表中获取数据以显示为纯文本

javascript - 替换文本框中数字以外的字符

javascript - 如何在不使用其模块名称的情况下为类创建新对象?

javascript - 如何在 botpress 自定义组件中获取 json 对象?

javascript - 使用 ES6 导入 JSNLog 的正确语法是什么?

javascript - Bootstrap-选择数据实时搜索,按数据标记和值搜索

jQuery 工具提示 - 如何声明 2 个选项

jquery - HTML5 音频和 jQuery

javascript - 通过replace()方法将年份放在括号中