jquery - 在事件处理程序中选择具有类的子 div

标签 jquery jquery-selectors parent-child children

我不知道如何做到这一点

我有

<div class="a parent">
 <div class="child">
 </div>
</div>
<div class="b parent">
 <div class="child">
 </div>
</div>

我想要这样的东西(伪代码)

$(".parent").mousemove(function(){

 select the `.child` which is the child of this div


})

因此,当将 .a 悬停在其上时,它将仅选择 a 的 .child,而当将 .b 悬停在其上时,它将选择 b 的仅.child

这应该涉及 this$this$(this) 或类似的东西..但它令人困惑,我不知道哪里可以阅读相关内容

最佳答案

这将选择具有 .child 类的所有子级。

$(".parent").mousemove(function() {
    var children = $(this).children('.child');
});

这样,您就可以使用 .eq() 方法选择第一个子项。

if (children.length > 0) {
    var firstChild = children.eq(0);
}

您还可以使用函数 .find() 从后代(从 child 的 child ...)中进行选择,这不是问题的一部分,但相关且有用。

var descendants = $(this).find('.child');

关于jquery - 在事件处理程序中选择具有类的子 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15597689/

相关文章:

jquery - 如何使用 :not selector? 忽略多个类

javascript - :contains issue on IE8

jQuery 多个parent() 调用

javascript - 阻止对父级的相同域 iframe 访问

php - 无需插件即可在表单外上传 Ajax 文件

javascript - 为什么我的 for 循环卡住了?

javascript - JavaScript/jquery 中的内存泄漏在哪里?

jQuery:删除 HTML 元素,同时保留其子元素

html - ul 中的文本居中,带有 float 的 li's

jquery - 使用 CSS 进行图像定位。 (涉及一点 jQuery)