<div class="box">
<div class="content selected">
<h2>.parents() 的效果</h2>
<h3>使用方式一</h3>
<ul>
<li>取得所有 li 元素的所有匹配的祖先元素,直到根元素</li>
<li class="target-1">設定所有祖先元素的背景顏色</li>
</ul>
<h3>使用方式二</h3>
<ul class="selected">
<li>取得所有 li 元素的祖先元素,並且元素的 class 有 "selected" </li>
<li>設定匹配的祖先元素背景顏色</li>
<li class="target-1 target-2">只設定匹配的元素,因此使用方法一的ul不會被設定背景顏色</li>
</ul>
</div>
<div class="field is-grouped">
<button class="button is-link example-1">使用方式一</button>
<button class="button is-info example-2">使用方式二</button>
<button class="button reset">reset</button>
</div>
</div>
xxxxxxxxxx
ul {
background-color: DimGrey;
}
// 使用方式一
$('.example-1').on('click', function() {
$('.target-1').parents().css('background-color', 'DodgerBlue');
});
// 使用方式二
$('.example-2').on('click', function() {
$('.target-2').parents('.selected').css('background-color', 'LightSkyBlue');
});
// reset
$('.reset').on('click', function() {
$('*').css('background-color', '');
});