我想检查最近的<p>
中的内容,并相应地向div中添加一个类。
在这里我被困住了。
$('p').each(function () {
if ($('p').text() == 'E. A. K') {
$('.pl1').addClass('service');
}else{
$('.pl2').addClass('service');
}
});
.service:after{content:"(service)"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>E. A. K.</p>
<p>F. F.</p>
<span class=pl1>Player 1</span><br>
<span class=pl2>Player 2</span>
SO
如果第一个<p>
是E. A. K.,那么.pl1
的类为service
如果第一个<p>
是F。那么.pl2
的类是service
请考虑有许多<p>
都具有这两个内容。
并且会不时添加一些新内容。
答案 0 :(得分:2)
首先,您需要稍微加快速度,并确保将括号放在正确的位置。
您说the <p> that appears closest to the top of the body
,那么您只想要1,因此无需遍历每个<p>
这应该做您想要的,但是仍然不确定,因为您的逻辑有点奇怪,无论如何希望它会有所帮助。
$('body p:first').filter(function() {
if ($(this).text() == 'E. A. K.') {
$('.pl1').addClass('service');
} else {
$('.pl2').addClass('service');
}
});
演示
$('body p:first').filter(function() {
if ($(this).text() == 'E. A. K.') {
$('.pl1').addClass('service');
} else {
$('.pl2').addClass('service');
}
});
.service:after {
content: "(service)"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>E. A. K.</p>
<p>F. F.</p>
<span class=pl1>Player 1</span><br>
<span class=pl2>Player 2</span>
答案 1 :(得分:0)
$('p:first').map(function() {
if ($(this).text() == "E. A. K.") {
$('.pl1').addClass('service');
} else {
$('.pl2').addClass('service');
}
});
.service {
color: red;
}
.service:after {
content: "(service)"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>E. A. K.</p>
<p>F. F.</p>
<span class="pl1">Player 1</span><br>
<span class="pl2">Player 2</span>