0

我正在尝试从具有类和/或 id 的 2 个父 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'); });

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

在此先感谢您的帮助!

4

4 回答 4

4

小提琴

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

尝试这个。如果你需要它更具体,你可以做些input[type="text"]什么。

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

于 2013-08-13T19:46:52.417 回答
1

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

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

http://jsfiddle.net/MxffP/

于 2013-08-13T19:47:48.123 回答
0

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

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

工作jsfiddle:

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

于 2013-08-13T19:54:07.657 回答
0

这是[演示]

$(".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'); });
于 2013-08-13T19:47:17.390 回答