选择没有ID或类名的子项

Selecting Children without ID or Class names

本文关键字:ID 选择      更新时间:2023-09-26

我正试图从两个具有类和/或id的父div中选择一个输入文本框。这样做的例子和方法太多了,我尝试了太多,以至于我不得不发布这个问题,以备其他人可能遇到这个问题时提供帮助。

代码

<div class="tblsearch">
    <div id="ElementCount10_filter" class="dataTables_filter">
        <label>
            Search:
            <input type="text">
        </label>
    </div>
    <div id="ElementCount10_info" class="dataTables_info"></div>
    <div class="clear"></div>
 </div>

我尝试过以下几种:

$(this).parent(".dataTables_filter").children("label").children("input").click(function () { alert('we got here'); });
$(".tblsearch.dataTables_filter label > input").click(function () {
    alert('hovered');
});
$(this).parent(".dataTables_filter").children("input").click(function () { alert('we got here'); });

我无法访问选择器。我需要检查是否有人点击了框并启动了一个功能。这看起来非常简单,我的语法中一定遗漏了一些东西。

提前感谢您的帮助!

fiddle

$('.dataTables_filter').on('click', 'input', function() {
    alert('here we are!');
});

试试这个。如果你需要更具体的,你可以做input[type="text"]之类的。

这使用事件委派(有关更多信息,请参阅@Methletics的链接)。因此,这将处理父级中任何input上的任何单击。

第二个选择器的问题是类名之间没有空格,包括一个空格会使它像预期的那样工作,因为.tblsearch类的<div>.dataTables_filter类的<div>祖先

$(".tblsearch .dataTables_filter label > input")

http://jsfiddle.net/MxffP/

这是[DEMO]。

$(".dataTables_filter").children("label").children("input").click(function () { alert('we got here'); });
$(".dataTables_filter label > input").click(function () {
    alert('hovered');
});
$(".dataTables_filter").find("input").click(function () { alert('we got here'); });

children只向下搜索一级。要向下搜索多个级别,请改用find

http://api.jquery.com/find/

工作jsfiddle:

http://jsfiddle.net/Vs5zZ/2/