jQuery's removeClass or toggleClass not working in ie8? Why? How do I get it to work correctly?
The following example works fine in Firefox and Opera, but not in ie8. However, if I turn compatibility mode on in ie8, it works correctly. Why? And how do I fix it?
The below example shows the use of toggleClass, but replacing this with addClass and removeClass still has the same problem.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" src="/jquery/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/jquery/js/jquery-ui-1.7.2.custom.min.js"></script>
<style type="text/css">
.dostuff{
background-color: green;
}
.undostuff{
background-color: red;
}
</style>
<script language="javascript">
$(document).ready(function(){
$('#DoStuffButton').click(function(){doStuff();});
$('#UndoStuffButton').click(function(){undoStuff();});
function doStuff(){
$('#test').html('Do some stuff');
$('#test').toggleClass('dostuff', 'slow', callback('dostuff'));
}
function undoStuff(){
$('#test').html('Undo some stuff');
$('#test').toggleClass('undostuff', 'slow', callback('undostuff'));
}
function callback(className){
setTimeout(function(){
$('#test').toggleClass(className, 'slow');
}, 1500);
}
});
</script>
</head>
<body>
<div id="test">Blah blah blah</div>
<div>
<button id="DoStuffButton" name="DoStuffButton开发者_开发技巧">Do some stuff</button>
<button id="UndoStuffButton" name="UndoStuffButton">Undo some stuff</button>
</div>
</body>
</html>
EDIT: Changing the javascript to the following also has the same problem in ie8. Any explanation why, and how to get it to work correctly?
function doStuff(){
$('#test').html('Do some stuff');
$('#test').addClass('dostuff', 'fast');
setTimeout(function(){$('#test').removeClass('dostuff', 'slow');}, 1000);
}
function undoStuff(){
$('#test').html('Undo some stuff');
$('#test').addClass('undostuff', 100);
setTimeout(function(){$('#test').removeClass('undostuff', 'slow');}, 1000);
}
It may be doing what you want it to on some browsers, but it's not doing it the way you think it is.
Firstly, your parameters to toggleClass don't match the API. so 'slow', callback('dostuff')
mean nothing to toggleClass.
Secondly, when you pass callback('dostuff')
you're passing the result of calling that function, you're not passing a reference to the function.
精彩评论