jquery - 类没有在焦点上被删除 - jQuery

标签 jquery css jquery-selectors

$("input.fee").focus(function() {
  $(this).closest("div.FirstLayer").removeClass("removeClass");
});
.removeClass {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mainWrapper">
  <div class="FirstLayer removeClass">
    <input class="foo" value="fooX" />
  </div>
  <div class="SecondLayer">
    <div class="thirdLayer">
      <input class="fee" />
    </div>
  </div>
</div>

为什么我的类(class)没有被移除焦点?

最佳答案

你的选择器是错误的

$("input.fee").focus(function(){
    $(this).closest("div.mainWrapper").find("div.FirstLayer").removeClass("removeClass");  
});

工作演示:

$("input.fee").focus(function() {
  $(this).closest("div.mainWrapper").find("div.FirstLayer").removeClass("removeClass");
});
.removeClass {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mainWrapper">
  <div class="FirstLayer removeClass"><input class="foo" value="fooX" /></div>

  <div class="SecondLayer">
    <div class="thirdLayer">
      <input class="fee" />
    </div>
  </div>
</div>


.closest(selector)

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.


问题

$("input.fee") 没有 ancestors 元素 div.FirstLayer,如下图所示。

enter image description here

解决方案

$("input.fee").closest("div.mainWrapper") 获取 ancestors 元素 div.mainWrapper 然后找到元素 div.FirstLayer

关于jquery - 类没有在焦点上被删除 - jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23244402/

相关文章:

html - 水平滚动不显示图像

jQuery AND 选择器

javascript - Grails:Ajax 参数未到达 Controller

jquery - 如何使粘性页脚适合其容器内部背景颜色

php - 使用 codeigniter 无法将动态输入值正确保存在数据库中

javascript - 为什么我的博客上有不需要的 css 和 js 文件?

javascript - 检查 Javascript 中的正整数 : performance and security

javascript - Jquery next() 问题

javascript - 添加目标时 CSS 焦点不起作用

javascript - 3个按钮之间的交互