好的,这看起来很简单,但我几个小时都无法解决。
以下是四个div.testName
,我想要的是:
如果div.testName
包含子div#wrong
,则必须将该类wrongParent
添加到该特定父级。
同样,如果div.testName
包含子div#right
,则必须将该类rightParent
添加到该特定父级。
现在,如果有3个div#wrong
,那么3个div.testName
也必须为每个wrongParent
分配3个div
。
我创建了小提琴here
请帮忙
$( "#right" ).each(function() {
$(this).parent().addClass('rightParent');
$('<span>i m right</span>').insertBefore('.testName .head > h3');
});
$( "#wrong" ).each(function() {
$(this).parent().addClass('wrongParent');
$('<span>i m wrong</span>').insertBefore('.testName .head > h3');
});
<div class="testName">
<div class="head">
<h3>wrong heading</h3>
</div>
<div id="wrong"></div>
</div>
<div class="testName">
<div class="head">
<h3>wrong heading</h3>
</div>
<div id="wrong"></div>
</div>
<div class="testName">
<div class="head">
<h3>right heading</h3>
</div>
<div id="right"></div>
</div>
<div class="testName">
<div class="head">
<h3>right heading</h3>
</div>
<div id="right"></div>
</div>
答案 0 :(得分:1)
将您的id
更改为class
$( ".right" ).each(function( ) {
$(this).parent().addClass('rightParent');
$('<span>i m right</span>').insertBefore($(this).prev());
});
$( ".wrong" ).each(function( ) {
$(this).parent().addClass('wrongParent');
$('<span>i m wrong</span>').insertBefore($(this).prev());
});
.testName {
width:90%;
float: left;
margin: 10px;
border: solid 4px grey;
}
.rightParent {
border: solid 4px green;
}
.wrongParent {
border: solid 4px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="testName">
<div class="head">
<h3>wrong heading</h3>
</div>
<div class="wrong">
</div>
</div>
<div class="testName">
<div class="head">
<h3>wrong heading</h3>
</div>
<div class="wrong">
</div>
</div>
<div class="testName">
<div class="head">
<h3>right heading</h3>
</div>
<div class="right">
</div>
</div>
<div class="testName">
<div class="head">
<h3>right heading</h3>
</div>
<div class="right">
</div>
</div>