考虑这个标记:
<div class="click">click</div>
<div class="container">
<div>
<div data-attr="color">blue</div>
<div data-attr="color">red</div><!-- this is the only n-th child div to be red -->
<div data-attr="color">red</div>
<div data-attr="color">red</div>
</div>
</div>
<div class="click">click</div>
<div class="container">
<div>
<div data-attr="color">blue</div>
<div data-attr="color">red</div><!-- this is the only n-th child div to be red -->
<div data-attr="color">red</div>
<div data-attr="color">red</div>
</div>
</div>
这个脚本:
<script>
$(document).ready(function () {
$('.click').click(function () {
$('.container div').each(function (i) {
if ($(this).attr('data-attr') == "color" && $(this).html() == "red" && $(this).prevUntil('.container').filter(function (i) {
return $(this).attr('data-attr') == "color" && $(this).html() == "red"
}).length == 0) {
$(this).css('color', 'red');
}
});
});
});
</script>
也就是说,我希望匹配元素只有在它是第一个时才为红色。我的问题是我被限制使用另一个结构的脚本,所以只有ThisIsFirstInsideItsClosestParentContainer
其中的一部分if()
必须重写,而这个脚本的其余部分必须保持不变。
<script>
$(document).ready(function () {
$('.click').click(function () {
$('div').filter(function (i) {
return $(this).attr('data-attr') == "color" && $(this).html() == "red"
}).each(function (i) {
if (ThisIsFirstInsideItsClosestParentContainer) {
$(this).css('color', 'red');
}
});
});
});
</script>
此外,我非常不喜欢在我的情况下使用 prevUntil() ,但我还没有找到另一种方法。那么,ThisIsFirstInsideItsClosestParentContainer
不使用 prevUntil() 应该是什么样子?
编辑
请告诉我为什么这不起作用
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.click').click(function () {
$('.container [data-attr]').filter(function (i) {
return $(this).attr('data-attr') == "color" && $(this).html() == "red"
}).each(function (i) {
if ($(this).index() == 0) {
$(this).css('color', 'red');
}
});
});
});
</script>
</head>
<body>
<div class="click">click</div>
<div class="container">
<div>
<div data-attr="color">blue</div>
<div data-attr="color">red</div><!-- this is the only n-th child div to be red -->
<div data-attr="color">red</div>
<div data-attr="color">red</div>
</div>
</div>
<div class="click">click</div>
<div class="container">
<div>
<div data-attr="color">blue</div>
<div data-attr="color">red</div><!-- this is the only n-th child div to be red -->
<div data-attr="color">red</div>
<div data-attr="color">red</div>
</div>
</div>
</body>
</html>