gpt4 book ai didi

javascript - jQuery - 选择具有特定 html 的元素

转载 作者:搜寻专家 更新时间:2023-10-31 22:10:48 26 4
gpt4 key购买 nike

我尝试选择一个具有特定 html 的 div。看我的例子:

$("#clickMe").click(function(){
$("div:contains('heinrich')").css("background-color", "limegreen")
});
.normal {
width: 100px;
height: 100px;
display: inline-block;
}
.red {
background-color: red;
border: 1px solid black;

}
.blue {
background-color: blue;
border: 1px solid black;
}
.yellow {
background-color: yellow;
border: 1px solid black;
}

#masterdiv {
border: 10px solid gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="masterdiv">
My favorite frends are:
<div class="red normal" id="div1">
hans
</div>
<div class="blue normal" id="div2">
franz
</div>
<div class="yellow normal" id="div3">
heinrich
</div>
</div>

<button id="clickMe">
Clicking me should make only heinrichs div limegreen
</button>

jsFiddle: https://jsfiddle.net/fj1brnv8/2/

但是,父 div 的颜色也会发生变化。有没有办法只选择元素本身,我不允许使用 ID。

最佳答案

最好在选择器中提及 className $("div .normal:contains('heinrich')")

$("#clickMe").click(function(){
$("div .normal:contains('heinrich')").css("background-color", "limegreen")
});
.normal {
width: 100px;
height: 100px;
display: inline-block;
}
.red {
background-color: red;
border: 1px solid black;

}
.blue {
background-color: blue;
border: 1px solid black;
}
.yellow {
background-color: yellow;
border: 1px solid black;
}

#masterdiv {
border: 10px solid gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="masterdiv">
My favorite frends are:
<div class="red normal" id="div1">
hans
</div>
<div class="blue normal" id="div2">
franz
</div>
<div class="yellow normal" id="div3">
heinrich
</div>
</div>

<button id="clickMe">
Clicking me should make only heinrichs div limegreen
</button>

关于javascript - jQuery - 选择具有特定 html 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44801647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com