Why this class assignment is not working in IE
I've wrote this peice of code, this works fine in FF and Chrome but not in IE. Why is it?
<html>
<header>
<style type="text/css">
.red{
color: red;
}
.green{
color: green;
}
.yellow{
color: yellow;
}
</style>
</header>
<body>
<div id="mydiv" style="height: 50px">Some contents</div>
<div>
<input type="radio" value="1" name="change" onclick="onClick(this)">Red</input>
<input type="radio" value="2" name="change" onclick="onClick(this)">Green</input>
<input type="radio" value="3" name="change" onclick="onClick(this)">Yellow</input>
</div>
<script type="text/javascript">
function onClick(el){
var className = "";
if(el.value == 1){
className = "red";
}else if(el.value == 2){
className = "green";
}else if(el.value == 3){
className = "yellow";
}
document.getElementById("mydiv").setAttribute("class", cla开发者_如何转开发ssName);
}
</script>
</body>
</html>
Arun's correct about the solution being .className
instead. On top of that, I'd simplify things quite a bit with an object map, like this:
var classMap = { "1":"red", "2":"green", "3":"yellow" };
function onClick(el){
document.getElementById("mydiv").className = classMap[el.value];
}
IE does not support the setAttribute method for class attribute.
You can solve this issue by using document.getElementById("mydiv").className = className;
instead of document.getElementById("mydiv").setAttribute("class", className);
.
But I think if you use a framework like jQuery you can forget about these kind of browser compatibility issues.
<html>
<header>
<style type="text/css">
.red{
color: red;
}
.green{
color: green;
}
.yellow{
color: yellow;
}
</style>
</header>
<body>
<div id="mydiv" style="height: 50px">Some contents</div>
<div id="ctrls">
<input type="radio" value="1" name="change" divClass="red">Red</input>
<input type="radio" value="2" name="change" divClass="green">Green</input>
<input type="radio" value="3" name="change" divClass="yellow">Yellow</input>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var mydiv = $("#mydiv");
var myctrls = $("#ctrls").delegate("input[name='change']", "click", function(e){
var el = $(e.currentTarget);
mydiv.removeClass(mydiv.attr("class")).addClass(el.attr("divClass"));
});
});
</script>
</body>
</html>
精彩评论