如何使用jQuery替换另一个类?

时间:2012-01-08 06:44:37

标签: javascript jquery

我可以用什么jquery将下面使用的类从indent_1更改为indent_2或indent_4到indent_2?我知道删除类,但是当类是变化的名称时我怎么能这样做呢?

<div class="rep_td0 indent_1" id="title_1">Menu two</div> 
or 
<div class="rep_td0 indent_4" id="title_1">Menu two</div>

5 个答案:

答案 0 :(得分:3)

试试这段代码,

$("#title_1").removeClass("indent_1").addClass("indent_2");

如果你不确定哪个可用,请试试这个

$("#title_1").removeClass("indent_1").removeClass("indent_4").addClass("indent_2");

更新:

$("#title_1").removeClass(function() {
    var match = $(this).attr('class').match(/\bindent_\d+\b/);
    if (match) {
        return (match[0]);
    } else {
        return ("");
    }
}).addClass("indent_2");

答案 1 :(得分:2)

由于你还没有确切地说明你想要改变到另一个班级的哪个班级,并且你说你想要处理你不确切知道班级是什么的情况,这里有一些想法:

您可以使用此选择器找到所有具有以“indent_”开头的类的对象:

$('[className^="indent_"]')

如果你想检查每个对象上的类,你可以用.each()迭代那个jQuery对象,并决定如何处理每个对象,或者你可以将removeClass()与自定义函数一起使用,检查班级名称并决定如何处理它。

如果您只是想将所有缩进类名更改为indent_2,那么您可以使用:

$('[className^="indent_"]').removeClass("indent_1 indent_3 indent_4").addClass("indent_2");

或者,使用可以使用正则表达式检查类名的自定义函数:

$('[className^="indent_"]').removeClass(function(index, name) {
    var match = name.match(/\bindent_\d+\b/);
    if (match) {
        return(match[0]);
    } else {
        return("");
    }
}).addClass("indent_2");

或者,如果您要做的只是找到id =“title_1”的对象并修复它的类名,您可以这样做:

var o = document.getElementById("title_1");
o.className = o.className.replace(/\bindent_\d+\b/, "indent_2");

您可以在此处查看最后一项工作:http://jsfiddle.net/jfriend00/tF8Lw/

如果你想把它变成一个可以使用不同数字的函数,你可以使用它:

function changeIndentClass(id, indentNum) {
    var item = document.getElementById(id);
    item.className = item.className(/\bindent_\d+\b/, "indent_" + indentNum);
}

答案 2 :(得分:1)

尝试以下:

$('#title_1').removeClass('indent_1').addClass('indent_2');

此处,indent_1类将替换为indent_2

答案 3 :(得分:0)

也许这个?:Remove all classes that begin with a certain string

回答了如何替换具有特定前缀的jQuery元素上的类名,例如'indent _'。

虽然该答案并未专门针对替换,但您可以通过稍微改变其中一个答案来实现这一目标:

$("selector").className = $("selector").className.replace(/\bindent.*?\b/g, 'indent_2');

或类似......

答案 4 :(得分:0)

首先要做的事情......如果您的页面上有多个元素具有完全相同的ID,那么您将无法通过ID选择它们。有些浏览器根本不起作用,而其他浏览器可能只返回匹配的第一个元素。

所以你必须先清理身份证件。

您可以使用带有选择器的启动来查找与您的类名模式匹配的所有类,然后决定是否要切换它们:

$('[class^="indent_"]').each(function() {
   var me = $(this);
   if(me.hasClass("indent_1").removeClass("indent_1").addClass("indent_2");
});