jQuery选择器语法问题

时间:2009-12-09 18:22:49

标签: jquery jquery-selectors

这是我的HTML:

<form>
    <dl>
        <dt>&nbsp;</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的{​​{1}}。我怎么做这种选择?

更新:也许我需要澄清一下:在检查dt的内容是否也是&nbsp;之前,有几个人在隐藏dd的地方发布了答案。在隐藏dt和dd之前,两个条件都必须为真。

最终解决方案:以下是我最终的结果:

&nbsp;

5 个答案:

答案 0 :(得分:3)

$("input[type=hidden]").filter(function() {
    return $(this).parent().prev('dt').html() === "&nbsp;";
}).each(function() {
    $(this).parent().hide().prev().hide();
});

这不会选择<dt>foo&nbsp;bar</dt>

contains('&nbsp;')会。

更简洁(信用Emil's answer

$("input[type=hidden]").filter(function() {
    return $(this).closest('dd').prev('dt').html() === "&nbsp;";
}).closest('dd').hide().prev('dt').hide();

答案 1 :(得分:1)

使用contains选择器:

$("dt:contains('&nbsp;')").hide();

答案 2 :(得分:1)

$("input[type=hidden]").each(function() {
    $(this).closest('dd').hide()
           .prev('dt').hide();
});

此代码找到带有标记dd的输入的最近父级,隐藏它,然后查找dt兄弟并隐藏它。

答案 3 :(得分:0)

包含选择器与整个内容不匹配,因此它可能适合您,但不是理想的解决方案。正确的方法是使用过滤功能:

$('input[type=hidden]').filter(function() {
   return $(this).prev().html() == '&nbsp;'
})
.each(function() {
   $(this).hide();
   $(this).prev().hide();
});

答案 4 :(得分:0)

这也可以解决问题(改编自早期版本的cobbal的答案):

$("input[type=hidden]").each(function() {
    if ($(this).parent().prev().filter(function() {
        return $(this).html() === "&nbsp;";
    }).hide().length > 0) {
        $(this).hide();
    }
});
相关问题