javascript - 是否有可能在 JS 和 jQuery 中处理除 'this' 之外的同一类的所有元素

标签 javascript jquery html this

当我使用this时对于同一类的各种元素,JS/jQuery 是否有可能使用类似 all elements except that one selected 的东西为了少写代码?

$('.field').focus(function() {
  $(this).css('border-bottom','3px solid red');
 $(all other elements of the class .field). $(this).css('border-bottom','3px solid grey');
});

最佳答案

您可以使用.not(this)

var fields = $('.field').focus(function() {
  fields
    .css('border-bottom','3px solid grey')
    .not(this).css('border-bottom','3px solid red');
});

在下面添加了一个使用 .not 的简单示例来说明其工作原理。希望这有帮助

var fields = $('.field').on('click', function() {
  fields
   .css('border','3px solid grey')
   .not(this).css('border','3px solid red');
});
.selected {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field">One</div>
<div class="field">Two</div>
<div class="field">Three</div>
<div class="field">Four</div>
<div class="field">Five</div>

对于这个特定场景,您也可以在不使用 .not() 的情况下执行类似的操作

var fields = $('.field').focus(function() {
  fields.css('border-bottom','3px solid grey');
  $(this).css('border-bottom','3px solid red');
});

关于javascript - 是否有可能在 JS 和 jQuery 中处理除 'this' 之外的同一类的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31441467/

相关文章:

javascript - Jquery 星级评定在 Firefox 和 Chrome 中不起作用

Javascript:避免多个弹出框/检查div是否为空

javascript - iOS 设备上 HTML5 Canvas 中 Javascript 的 setTimeout 问题

javascript - 将 DOM 元素的属性/值对转换为 Javascript 对象?

javascript - 更新月/年变化的日期字段 -Jquery 日期选择器

javascript - 从服务器下载 zip excel 文件

jquery - 全日历着色特定单元格

javascript - 解析一行文本并在给定单词之前动态插入换行符?

javascript - “Is there an JavaScript function for finding the browser Content Text using mouse hover element?”

javascript - 单击按钮时更改嵌入式 youtube 视频中的时间