可以使用$(this)和通用选择器(*)

Is possible to use $(this) and universal selector (*)?

本文关键字:选择器 this 可以使      更新时间:2023-09-26

我想知道是否可以将通用选择器与$(this)一起使用。例如,当我想从元素及其子元素中删除所有内联CSS时,我使用以下代码:

$('#element, #element *').attr('style','');

但如果我有$(this),代码是什么?

也许我得试试:

 $(this, this+'*').attr('style','');

您可以使用find()

$(this).find('*').attr('style','');

或上下文选择器

$('*', this).attr('style','');

this 做与$('#element *')相同的事情

如果this表示的元素应该是集合的一部分,则可以将其添加回

$(this).find('*').addBack().attr('style','');

我倾向于同意Rory McCrossan在评论中的观点,使用父元素和外部样式比更改多个元素的样式属性更可取

.element.styled * { /* styles for all children */ }

然后只是

$('.element').removeClass('styled')

删除子上的样式

您可以找到孩子,然后使用removeAttr

$(this).children().removeAttr('style');

$(this).find('*').removeAttr('style');

jQuery查找方法将起作用:

$(this).find(selector);

您可以使用jQuery的.children():

$(this).children().attr('style','');

然而,这只会降低一个级别,所以您也可以使用.find():

$(this).find('*').attr('style','');

看看https://jsfiddle.net/joe_young/zofhwca6/

您可以使用这个:

$(this).find('*').removeAttr('style');

甚至上下文:

$('*', this).removeAttr('style');

$(this).children()可用于选择其子级此外,您可以像$(this).children('.classname') 一样进行特定

类似地,$(this).parent()可以用于选择其父