Hi I have a question regarding simple Javascript function. Below is the code its easily visible that when a user clicks on the click button I want to switch classes I mean when the page loads "This is para" needs to be displayed then when the user clicks on click button the text needs to change to This is updated. but dont know why its not working.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>untitled</title>
<script type="text/javascript" src="jquery.js"></script>
<style type="text/css">
.none {
display: none;
}
.display1 {
display: block;
}
</style>
</head>
<body>
<p id="default">This is para</p>
<p id="updat开发者_如何学JAVAed" style="display:none">This is updated</p>
<p><input type="button" value="Click" id="button1" /></p>
<script type="text/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$("#default").addClass("none");
$("#updated").addClass("display1");
});
});
</script>
</body>
</html>
Do this instead:
$("#default").hide();
$("#updated").show();
And you can get rid of the none
and display1
classes.
What's happening to you is that the style="display:none"
takes precedence over a class, so it will never show that way.
Why are you not just using show()
and hide()
?
<script type="text/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$("#default").hide();
$("#updated").show();
});
});
</script>
If you just want to change the text, instead of having two elements, why not remove the updated
element and use .text()
, like so:
<script type="text/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$("#default").text("This is updated");
});
});
</script>
Your "addClass" call is (probably) working, but the style directly on the element trumps the style offered by the CSS.
Personally I prefer to do that sort of thing by changing "class" values like that, but you can't really mix and match the two approaches. (Well, you can, but it's confusing and error-prone.) Instead of starting your element with that style, give it instead your "none" class.
精彩评论