如何使用“this”作为选择器的一部分
How do I use "this" as a part of a selector?
我试着这样做:
$(this + ' li:not(:nth-last-child(2)):not(:last-child)').hide()
完整代码示例:
$('.comments').each(function(){
$(this + ' li:not(:nth-last-child(2)):not(:last-child)').hide()
var template = $('#expand').html();
$(this).prepend(template)
});
我需要将其作为"each"函数运行,因为我想稍后输入条件。
试试这个:
$('li:not(:nth-last-child(2)):not(:last-child)', this).hide();
从文档
jQuery( selector [, context] )
选择器 - 包含选择器表达式的字符串
context - 用作上下文的 DOM 元素、文档或 jQuery
因此,您可以使用this
作为上下文参数:
$('.comments').each(function(){
$('li:not(:nth-last-child(2)):not(:last-child)', this).hide()
var template = $('#expand').html();
$(this).prepend(template)
});
如果你想找到this
中的所有li:not(:nth-last-child(2)):not(:last-child)
,你可以使用find()
:
$(this).find('li:not(:nth-last-child(2)):not(:last-child)').hide();
另外值得注意的是,如果您知道要查找的元素只会深一层,那么您应该使用 children()
而不是 find()
.
这是一个对象,而不是一个字符串,您可以将其他字符串附加到该字符串以构建所需的选择器。
只需使用 find() 遍历代码:
$('.comments').each(function(){
$(this).find('li').not(':nth-last-child(2)').not(':last-child').hide();
var template = $('#expand').html();
$(this).prepend(template);
});
相关文章:
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- 在动态创建的元素上获取对特定选择器的引用
- AngularJS-在JSON选择器中使用变量名
- 每当您在选择器内移动鼠标时,悬停功能就会重复
- 使用CSS或js,使用动态选择器选择任意li的下一个元素
- jQuery最近父级的数据属性选择器
- 为什么不'在JQuery中找到第二个css选择器的工作
- 为什么 .focus() 不起作用,而 .css(“color”,“red”) 在同一个选择器上起作用
- jquery IE7中的第n个选择器
- Webdriver.io pageObject模式-通过传递参数来定义元素选择器
- jquery日期选择器年份范围默认值
- jquery日期选择器失去了交互性
- 正在搜索JavaScript日期选择器滑块
- 如何将返回的值应用于多个不同位置的多个选择器
- 每个选择器的Jquery css颜色都在变化,但字体大小却没有变化
- 如何在多个jQueryUI日期选择器中屏蔽特定日期
- jquery日期选择器显示与值不同的文本
- jQuery选择器无法正常工作
- 文档就绪提供了错误的选择器高度
- 如何使用“this”作为选择器的一部分