这是我的 html:
<form>
<dl>
<dt> </dt>
<dd><input type="hidden"></dd>
<dt>Dont hide this one</dt>
<dd><input type="text"></dd>
</dl>
</form>
我使用 jQuery 隐藏 dt
/dd
元素,其中使用以下代码隐藏输入类型:
$("input[type=hidden]").each(function() {
$(this).parent().hide().prev().hide();
});
但我也只想将其应用于文本为
的 dt
。我怎样才能进行这种选择?
更新:也许我需要澄清一下:有些人已经发布了答案,其中它在检查 dt 的内容是否也是
之前隐藏了 dd。在隐藏 dt 和 dd 之前,这两个条件都必须为真。
最终解决方案:这是我最终得到的结果:
$('input[type=hidden]').filter(function() {
return $(this).closest('dd').prev('dt').html() === ' ';
}).each(function() {
$(this).closest('dd').hide()
.prev('dt').hide();
});
最佳答案
$("input[type=hidden]").filter(function() {
return $(this).parent().prev('dt').html() === " ";
}).each(function() {
$(this).parent().hide().prev().hide();
});
这不会选择<dt>foo bar</dt>
其中contains(' ')
会的。
更简洁(归功于Emil's answer)
$("input[type=hidden]").filter(function() {
return $(this).closest('dd').prev('dt').html() === " ";
}).closest('dd').hide().prev('dt').hide();
关于jQuery 选择器语法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1875807/