当我使用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/