【问题标题】:JQuery - remove selected class when using "Attribute starts with" selector?JQuery - 使用“属性开始于”选择器时删除选定的类?
【发布时间】:2013-03-26 01:32:34
【问题描述】:

使用带有变量类名的自动生成的 html 代码:table-col-44, table-col-19, table-col-121

我有一个循环,使用this jQuery selector functionality 选择这些变量类:

for(r in replace){
    var targ = replace[r];
    $("[class^='"+targ+"']").each(function(){
        ...
    })
}

问题是,一旦我选择了我想要清理的类,我就无法找到一种方法来定位它们以删除它们。通常这些是 <p><td> 标记,它们具有需要保留的其他类,因此我不能完全擦除类属性。有没有办法将匹配的类作为参数传递给 each() 函数?或者,jQuery 附带了某种$(this).removeClass([selected]) 关键字?完全被这里难住了。感谢您的帮助!

【问题讨论】:

  • 感谢您的意见。仅当所讨论的类是列表中的第一个类时才有效 - 不幸的是,大多数情况下,此代码并非如此。
  • 您的选择器"[class^='"+targ+"']" 只会选择第一类。
  • 我认为这是不正确的。我已经使用这种方法成功地选择了与第 2 类或第 3 类匹配的元素。
  • 我错了,你是对的。 *= 而不是 ^= 是选择任何类所必需的。

标签: jquery regex jquery-selectors


【解决方案1】:

不确定是否有更多的 jQuery 方式来执行此操作,但您可以在 each 中尝试:

var newClassName = $(this).attr('class').split(' ').slice(1).join(' ')
$(this).attr('class', newClassName)

这将删除第一个类名,因为您已与 ^= 匹配。

更新:

有关通过将函数传递给 removeClass 来删除类的示例,请参见此处:http://jsfiddle.net/DHxNG/1/。 JS是:

targ = 'table-col';
$('[class*="'+targ+'"]').removeClass(function(index, css) {
    var re = new RegExp(targ+"-\\d+");
    return (css.match(re) || []).join(' ');
});

这是基于此处的代码:JQuery removeClass wildcard

【讨论】:

  • ^= 匹配所有以输入字符串开头的类,而不仅仅是第一个。无论它出现在类名列表中的哪个位置,都希望删除该类。
  • 对我来说似乎不是这样,我需要使用*= 而不是^=
  • 太棒了!那确实是我的误会。向您致敬,先生。
【解决方案2】:

您可以将startsWith 函数添加到string 对象的原型,执行如下操作:

if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str){
        return this.indexOf(str) == 0;
    };
}

然后,您的循环删除以匹配项开头的类,如下所示:

for(r in replace) {
    var targ = replace[r];
    $("[class^='"+targ+"']").each(function() {
        var $element = $(this);
        var classes = $(this).attr('class').split(' ');
        for(var i = 0; i < classes.length; i++) {
            var cssClass = classes[i];
            if(cssClass.startsWith(targ)) {
                $element.removeClass(cssClass);
            }
        }
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-08
    • 2012-05-14
    • 2021-07-23
    • 2016-03-25
    • 2014-09-27
    • 2022-08-05
    • 2014-05-21
    相关资源
    最近更新 更多