没有父级的jquery子选择器
我正在查看教程中的一些代码,用于创建旋转木马菜单,并注意到没有父级的父级子选择器。 从来没有见过这个,并且对它实际上做的事情感到困惑。
请参阅以下代码:
var $wrapper = $('> div', this).css('overflow', 'hidden'), $slider = $wrapper.find('> ul'), $items = $slider.find('> li'), $single = $items.filter(':first'), singleWidth = $single.outerWidth(), visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border currentPage = 1, pages = Math.ceil($items.length / visible);
教程: http : //jqueryfordesigners.com/jquery-infinite-carousel/
有一个父(或者在这种情况下是一个scope
),注意选择器中的this
关键字,它与插件所应用的元素有关。
jQuery的选择器允许您设置范围,它可以是任何jQuery元素对象。
考虑
$(".somediv").myplugin();
在插件里面
$("> div", this) is actually translated to $("> div", $(".somediv"))
看看我的一个问题,答案解释了jQuery的选择器。 在jQuery中选择后代元素的最快方法是什么?
这个带有上下文的选择器:
$('> div', this)
翻过来使用像这样的.find()
:
$(this).find('> div')
使用>
子选择器只是:
$(this).children('div')
其他人正在做同样的交易,他们可以使用.children()
,实际上这样做更有效率。
$('> div', this)
this
很重要。 它是使查询等于的上下文参数
$(this).children('div');
有关更多信息,请参阅$()
的文档 ; 它特别提到了这个:
在内部,选择器上下文是使用.find()方法实现的,因此
$('span', this)
等价于$(this).find('span')
。
$(this).find('> div')
表示“这是孩子的div
,等于$(this).children('div')
。