jquery或者JS怎么改class的名字

我的一段代码
<script language="javascript">
function xx(n){
if(n==1){
document.getElementById("whatsNew").style.display = "block";
document.getElementById("specialsDefault").style.display = "none";
document.getElementById("featuredProducts").style.display = "none";

document.getElementById("new_product").className = "on";
document.getElementById("specials_product").className = "off";
document.getElementById("featured_product").className = "off";
}
if(n==2){
document.getElementById("whatsNew").style.display = "none";
document.getElementById("specialsDefault").style.display = "block";
document.getElementById("featuredProducts").style.display = "none";

document.getElementById("new_product").className = "off";
document.getElementById("specials_product").className = "on";
document.getElementById("featured_product").className = "off";
}
if(n==3){
document.getElementById("whatsNew").style.display = "none";
document.getElementById("specialsDefault").style.display = "none";
document.getElementById("featuredProducts").style.display = "block";

document.getElementById("new_product").className = "off";
document.getElementById("specials_product").className = "off";
document.getElementById("featured_product").className = "on";
}

}
</script>
<div id="select">
<div id="new_product" onmouseover="xx(1);" class="on">New Arrivals</div>
<div id="specials_product" onmouseover="xx(2);">Top Sellers</div>
<div id="featured_product" onmouseover="xx(3);">Featured Picks</div>
</div>

现在的结果是,每个涵数的前三句都执行了,但后三句document.getElementById("......").className = "!!!";执行不了,也就是,样式虽然换了,class还是不变,怎么办,后三句哪错了啊

jquery可以使用attr()或prop()方法修改类名,javascript可以修改对象的className属性,关键代码如下:

$("#test").attr("class","blue");
$("#test").prop("class","blue");
document.getElementById("test").className = "blue";

实例演示如下:

1、HTML结构

<style>
.red{color:red !important;}
.blue{color:blue !important;}
</style>
<div id="test">我是示例DIV</div>
<input type="button" id="js" value="使用javascript方法修改类名为red"><br>
<input type="button" id="jq" value="使用jquery方法修改类名为blue"><br>

2、jquery代码

$(function(){
$("#jq").click(function() {
$("#test").attr("class","blue");
});
}); 
window.onload = function(){
document.getElementById("js").onclick = function(){
document.getElementById("test").className = "red";
}
}

3、效果演示

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-11-08
$("#test").attr("class","blue");$("#test").prop("class","blue");document.getElementById("test").className = "blue";
第2个回答  2013-12-05

    javascript: document.getElementById("XX").addClass("xxx");

    jquery: $("#id").atrr("class","classname");$("#id").removeAtrr("class","classname");

本回答被提问者采纳
第3个回答  2013-12-05
$("#id").css("class", " ");
第4个回答  2013-12-05
$('#new_product').attr('class','off');