我应该如何初始化此变量以与jQuery一起使用? [英] How should I initialize this variable for use with jQuery?

查看:77
本文介绍了我应该如何初始化此变量以与jQuery一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是创建一个作为特定类/id对象的变量. 例如,在第(5)和(8)行中,我对ID(鞋类轮播)进行了字面引用,我希望有一个代表鞋类轮播的变量. 问题是,如果我做类似的事情:

What I'd like to do is make a variable that is a specific class/id object. For example, on lines (5) and (8) where I do a literal reference of the ID, shoe-carousel, I want to have a variable that represents shoe-carousel instead. The problem is that if I do something like:

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

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

it'll work for line (5), not for line (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家伙的诀窍是什么呢?谢谢!

To me, it seems like the issue with line 8 is that the single-quotes (') being pushed in from the variable definition are ruining it; so, what's the trick to give to a new JS/jQuery guy like me? Thanks!

推荐答案

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

After first realizing I posted a not-appropriate answer, then reading comments under @Redmega's answer, I think that the most efficience response to the OP's issue is like this:

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')解决方案,但是这种方式对性能的影响可能较小.

While very close to the $fooCarousel.find('.slick-current img') solution, this way has probably the less performance impact.

实际上,正如@Redmega所指出的,它没有任何区别.

actually it doesn't make any difference, as pointed by @Redmega.

这篇关于我应该如何初始化此变量以与jQuery一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆