我希望能够找到一种方法来隐藏前面的 <td>
的内容(如果上面的内容为空)。我的 table 是这样设置的:
<tr>
<td class="firsttd">
</td>
</tr>
<tr>
<td class="nexttd">
Hide me if above TD is empty
</td>
</tr>
<tr>
<td class="firsttd">
</td>
</tr>
<tr>
<td class="nexttd">
Hide me if above TD is empty
</td>
</tr>
到目前为止:
$(".firsttd").each(function( index ) {
var dotlenght = $(this).html().length;
if (dotlenght < 1){
$(this).next('.nexttd').hide();
}
});
但无法使其正常工作。我不知道如何告诉 JQuery 要定位哪个元素。
有人能指出我正确的方向吗?
最佳答案
您需要使用:
$(this).parent().next().find('.nexttd').hide();
|| || ^^------find td `.nexttd`
|| ^^------Traverse to next tr
^^------Traverse to parent tr
此外,您不需要单独迭代元素。您可以使用 .filter()
函数定位所有第一个为空的 td 元素,并将完整代码缩小为:
$( "td.firsttd" ).filter(function(){
return $(this).html() == "";
}).parent().next().find('.nexttd').hide();
关于javascript - 如果元素为空隐藏下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30316424/