如何使用jQuery动态替换类的一部分

How to dynamically replace part of a class using jQuery?

本文关键字:一部分 替换 动态 何使用 jQuery      更新时间:2024-02-22

我有一个以z-开头的动态类。如何将z-动态更改为fa-加载?

From <a href="#" class="z-dynamic">Link</a>
to <a href="#" class="fa-dynamic">Link</a>

我只想替换班级的一部分,而不是整个班级。

您可以使用属性包含选择器,并使用回调函数调用attr来修改每个元素的属性。在我的示例中,我使用一个带有正则表达式的字符串replace方法来确保列表中以z-开头的所有类都被替换,并且只替换该字符串的那些实例。然后,只需将其包装在jQuery文档就绪包装器中,就可以开始了。

$(function(){
    //Select only the a tags with "z-" in the "class" attribute, and modify the attribute using a callback function.
    $('a[class*="z-"]').attr('class', function(index, attr) {
        //Return the updated string, being sure to only replace z- at the start of a class name.
        return attr.replace(/(^|'s)z-/g, 'fa-');
    });
});
$(document).ready(function(){
    var self = $("a.z-dynamic");
    self.attr("class", self.attr("class").replace("z-", "fa-"));
});

这将改变

From <a href="#" class="z-dynamic">Link</a>
to <a href="#" class="fa-dynamic">Link</a>

如果您已经有了对该节点的引用,那么您可以很容易地将一个小regex与.replace()一起应用于className。

anchor.className = anchor.className.replace(/z-/, 'fa-');