选择没有ID或类名的儿童

时间:2013-08-13 19:42:44

标签: javascript jquery html

我正在尝试从具有类和/或ID的2个父div中选择一个输入文本框。有很多这样做的例子和方法,我已经尝试了很多,以至于在其他人可能会遇到这个问题的情况下,我已经使用这个问题寻求帮助。

CODE

<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'); });

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

提前感谢您的帮助!

4 个答案:

答案 0 :(得分:4)

<强> fiddle

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

试试这个。如果您需要更具体,可以input[type="text"]或其他。

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

答案 1 :(得分:1)

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

.dataTables_filter的em> ancestor
$(".tblsearch .dataTables_filter label > input")

http://jsfiddle.net/MxffP/

答案 2 :(得分:0)

这是[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'); });

答案 3 :(得分:0)

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

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

工作jsfiddle:

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