javascript - 根据内容更改样式

标签 javascript jquery html css

我有一个html

<div class="common">
<p class="special">
    <p class="child">test1</p>
</p>
<p class="special">
    <p class="child">test2</p>
</p></div>

如您所见,我有两个样式相同但内容不同的段落,我只想更改内容包含“test1”的段落的样式, 写了这样的东西

$(".common").each(function () {
if ($(this).find('.special').find('.child').text() == "test1")
{
    $(this).find('.special').find('.child').css('background','red');
}});

但是样式应用于两个段落,在 javascript/jquery 中是否有任何解决方案来解决这个问题

最佳答案

您的 html 无效 - p 元素不能包含另一个 p 元素

<div class="common">
    <div class="special">
        <p class="child">test1</p>
    </div>
    <div class="special">
        <p class="child">test2</p>
    </div>
</div>

然后

$(".common .special .child").each(function () {
    if ($(this).text() == "test1") {
        $(this).css('background', 'red');
    }
});

演示:Fiddle

您的代码将在每个.common中找到第一个.special .child元素,如果它的文本与测试用例匹配,那么它会将样式应用于所有.special .child.common` 中的元素

关于javascript - 根据内容更改样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22604092/

相关文章:

html - 链接在 float div 中不起作用

html - 像素精度降低 2 个像素

javascript - 无法从index.html调用javascript函数

javascript - 第一次点击 - 更改 ul 高度,第二次点击 - 重置高度

javascript - map() 不保存新元素

javascript - JQuery 中的点击事件没有响应

javascript - 如何将 Highchart 放到 html 页面

javascript - Node js 事件监听器未按预期工作

javascript - 实现自动完成时出现 "this.source is not a function"错误

javascript - 如何使用jquery正确加载php文件