我尝试选择设置了类的表格的标题。换句话说:寻找具有 .red
类的元素,然后开始寻找该元素上方的 h3
元素。
$('.xred').closest('table').addClass('test').prev('h3').addClass('test');
.test { background-color: green; }
.xred { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Goal</h3>
<table>
<tr>
<td>Blabla</td>
<td class="xred">Red</td>
</tr>
</table>
工作正常,只要我不在 table 和 H3 之间放置任何东西。
我怎样才能实现它在其他元素介于两者之间时也能正常工作?
$('.xred').closest('table').addClass('test').prev('h3').addClass('test');
.test { background-color: green; }
.xred { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Goal</h3>
<div>The Problem DIV</div>
<table>
<tr>
<td>Blabla</td>
<td class="xred">Red</td>
</tr>
</table>
非常感谢!
最佳答案
我不完全确定您为什么要做如此低效的事情。您不能直接访问 html 吗?
如果你这样做,做这样的事情可能会容易得多?
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapperdiv>
<h3>Goal</h3>
<div>The Problem DIV</div>
<table>
<tr>
<td>Blabla</td>
<td class="xred">Red</td>
</tr>
</table>
</div>
脚本:
$('.xred').closest('table').parent().find("h3").addClass("test");
有一个包装器让这一切变得更容易,是吗?
话又说回来,我个人永远不会构建任何我需要进行如此多的 DOM 搜索的东西。这是非常低效的。我会推荐一个带有包装 div 的良好 html 结构,您可以像这样将其存储在变量中:
var $wrapperDiv = $('.wrapperDiv');
$('h3', $wrapperDiv).addClass("test");
但是,那只是我...
但为什么呢?
好吧,无论何时使用 prevAll
和 closest
等函数,您都在遍历整个 DOM。它会导致相当大的 CPU 使用率,并且在手机等较慢的设备上通常会出现滞后响应。它还会更快耗尽电池电量。
除此之外,当在函数之上堆叠函数时,您会注意到任何设备上的响应都滞后。
最佳做法是将任何静态包装器存储在一个变量中一次,这样您就不必经常遍历 DOM。然后,使用尽可能少的选择器来获得你需要的东西,因为又一次;每个选择函数都会再次遍历 DOM。这只是 CPU 密集型。
关于javascript - 在具有类别的表上方最近的 H3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39930543/