我有这个jsfiddle我在段落内有一些其他标签。有时有 2 个,有时有 3 个这样的标签。它们每个都有一个样式属性。我想要实现的是摆脱所有标签中的样式属性,并将样式属性仅保留给最后一个子标签。
例如这个:
<p>
<em class="match js-match" style="background-color: rgb(228, 255, 0); color: rgb(0, 0, 0);">
<em class="match js-match" style="background-color: rgb(98, 238, 120); color: rgb(0, 0, 0);">
<em class="match js-match" style="background-color: rgb(255, 0, 76); color: rgb(255, 255, 255);">
<anotation>Some text...</anotation>
</em>
</em>
</em>
</p>
应该看起来像这样:
<p>
<em class="match js-match" >
<em class="match js-match">
<em class="match js-match" style="background-color: rgb(255, 0, 76); color: rgb(255, 255, 255);">
<anotation>Some text...</anotation>
</em>
</em>
</em>
</p>
通过这个 jQuery 代码,我可以删除所有样式。但我不想要这样。我想要 <em>
之一<p>
内的标签保留风格。
document.onclick = function(){
$("em.match.js-match").css({ 'background-color' : '', 'color' : '' });
};
我调查过first-child
或last-child
或nth-child
但无法完成这项工作。任何帮助将不胜感激。
最佳答案
你也可以尝试这个
//$("em.match.js-match").css({ 'background-color' : '', 'color' : '' });
//$("em.match.js-match em.match.js-match").css({ 'background-color' : '', 'color' : '' });
$("em.match.js-match em.match.js-match em.match.js-match").css({ 'background-color' : '', 'color' : '' });
em{
width: 400px;
height: 30px;
margin: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<em class="match js-match" style="background-color: rgb(228, 255, 0); color: rgb(0, 0, 0)">
<em class="match js-match" style="background-color: rgb(98, 238, 120); color: rgb(0, 0, 0);">
<em class="match js-match" style="background-color: rgb(255, 0, 76); color: rgb(255, 255, 255);">
<anotation>Some text...</anotation>
</em>
</em>
</em>
</p>
关于javascript - 如何删除段落内其他标签的样式属性并仅保留一个带有样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63101437/