我想以这样一种方式使用jquery:not选择器:当一堆元素没有指定的类时,那么我想向其中的一个添加类。
我想要实现的是:
'当design-preview1,design-preview2,design-preview 3和design-preview 4没有类“selected”时,将类“selected”添加到“design-preview1”。
我试过了,但是没有用:
$(".design-preview1, .design-preview2, .design-preview3, .design-preview4").not(".selected").$(".design-preview1").addClass('selected');
});
任何帮助将不胜感激
新的
这是我完整的jQuery代码:
$('.pop-design1').click(function(){
$(".design-preview li:not(.design-preview2).selected").removeClass('selected');
$(".design-list li:not(.design-list2).selected").removeClass('selected');
$(".design-preview2").toggleClass('selected');
$(".design-list2").toggleClass('selected');
$(".overlay").toggle();
});
$('.pop-design2').click(function(){
$(".design-preview li:not(.design-preview3).selected").removeClass('selected');
$(".design-list li:not(.design-list3).selected").removeClass('selected');
$(".design-preview3").toggleClass('selected');
$(".design-list3").toggleClass('selected');
$(".overlay").toggle();
});
$('.pop-design3').click(function(){
$(".design-preview li:not(.design-preview4).selected").removeClass('selected');
$(".design-list li:not(.design-list4).selected").removeClass('selected');
$(".design-preview4").toggleClass('selected');
$(".design-list4").toggleClass('selected');
$(".overlay").toggle();
});
if ($('.design-preview1, .design-preview2, .design-preview3, .design-preview4').not('.selected').length) {
$('.design-preview1').addClass('selected');
基本上我想要的是当.design-preview1,.design-preview2,.design-preview3和.design-preview4没有显示或未选择时,我希望.design-preview1默认显示。
实时链接:
http://www.expertfrontend.com/test/2.html
最佳答案
根据您的问题的要求,您说过要使用.not()
来实现这一目标。下面是通过addSelectedClassIfNotExists()
函数执行此操作的方法。
您还可以重构您的点击监听器,因此您只能运行一个已定义的函数。在建议的更改之后,下面是从问题中修改后的代码的样子:
var previews = $('.design-preview1, .design-preview2, .design-preview3, .design-preview4');
function addSelectedClassIfNotExists() {
if (previews.not('.selected').length === previews.length) {
$('.design-preview1').addClass('selected');
}
}
function toggleClasses(num) {
$('.design-preview li:not(.design-preview' + num + ').selected').removeClass('selected');
$('.design-list li:not(.design-list' + num + ').selected').removeClass('selected');
$('.design-preview' + num).toggleClass('selected');
$('.design-list' + num).toggleClass('selected');
$('.overlay').toggle();
}
previews.click(function () {
toggleClasses(this.className.slice(-1));
addSelectedClassIfNotExists();
});
关于javascript - 如何使用jQuery :not selector for more than one element at a time,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29873849/