我有几个有两个类名的div,例如......
<div class="mainContainer">
<div class="container">
<div class="test word1.20">
</div>
<div class="container">
<div class="test word3.40">
</div>
</div>
如果第二类名称中存在小数,我想在结尾处删除小数和零,因此结果将类似于word12。请注意,我有几个像这样的div
我在想......
if .test has a decimal, do this {
$(".container .test").each(function() {
value1 = $(this).attr("class").replace(".", "");
value2 = $(this).attr("class").replace("0", "");
$(this).attr("class", value1);
$(this).attr("class", value2);
});
}
感谢您的见解!
答案 0 :(得分:0)
您可以操作.container
的HTML,如下所示:
$(function(){
processReplacement();
showResult();
});
processReplacement = function(){
$("div.test").each(function(){
var classes = $(this).prop('class');
var regex = /(\bword)(.*)\b/;
var decimalClassName = regex.exec(classes)[2];
var decimalClassNameFixed = parseFloat(decimalClassName).toString().replace('.', '');
$(this).prop('class', classes.replace(regex, "$1" + decimalClassNameFixed));
});
};
showResult = function(){
$('.test').each(function(){
$(this).text($(this).prop('class'));
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainContainer">
<div class="container">
<div class="test word1.20"></div>
</div>
<div class="container">
<div class="test word3.40"></div>
</div>
</div>