从jQuery属性选择器的结果中删除由jQuery属性选择器定义的类

问题描述 投票:2回答:2

基本问题,我只想针对以指定字符串结尾的类的所有元素上以指定字符串结尾的所有类,并删除这些类。

此代码不起作用,但它接近我想要的:

$('[class$="_active"]').removeClass($('[class$="_active"]'))

$('[class $ =“_ active”]')返回一个jQuery.fn.init对象,我可以使用.each(index,item)来处理它。我认为它会像item.removeClass一样简单($('[class $ =“_ active”]'))但是下面的代码也不起作用:

$('[class$="_active"]').each(function(index,item){
        item.removeClass($('[class$="_active"]'))
})

removeClass函数不适用于我的每个函数中的项目。此时我正在考虑对每个项目进行字符串化,在“_active”之前找出文本,将其与字符串一起从“_active”中删除,然后返回重组后的结果。但这对于一个我认为有一个我忽略的基本答案的基本问题来说太复杂了。

javascript jquery
2个回答
1
投票

您可以使用attribute containing selectorattribute ends with selector来获取具有以_active结尾的特定类的所有元素。要首先删除类,必须使用String#match方法从类列表中提取特定类(仅当元素有多个类时才需要)。

$('[class$="_active"],[class*="_active "]').each(function(){
    $(this).removeClass($(this).attr('class').match(/\S+_active\b/)[0])
    // or $(this).removeClass(this.className.match(/\S+_active\b/)[0])
})

0
投票

一个可爱的解决方案

$('[class$="_active"]').each(function(i){$(this).removeClass(this.className)})

这是我的jsfiddle链接,看看https://jsfiddle.net/dupinderdhiman/mgzf2boL/7/

© www.soinside.com 2019 - 2024. All rights reserved.