我可以使用什么 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>
最佳答案
由于您还没有非常具体地说明您想要更改为另一个类,并且您已经说过您想要处理您不知道该类到底是什么的情况,因此这里有一些想法:
您可以使用此选择器查找具有以“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);
}
关于javascript - 如何使用 jQuery 将一个类替换为另一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8775875/