问题
Here's my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(".social").hover(function() {
$("h1", this).hide();
$(".networks", this).fadeIn();
}, function() {
$(".networks", this).hide();
$("h1", this).fadeIn();
});
</script>
<style>
.networks {
display:none;
}
</style>
</head>
<body>
<div class="social">
<h1>Share this</h1>
<div class="networks">
<p>Twitter</p>
<p>Facebook</p>
</div>
</div>
</body>
</html>
when i try it in http://jsfiddle.net/ppksR/, it's really working but when i copy paste it in my dreamweaver, its not working. What did i miss??? Any help?
回答1:
jsfiddle is wrapping the JavaScript code in onLoad
, which you should do. Wrap the script contents in:
$(function () {
// your code
});
To have jsfiddle emulate what you are doing, change the onLoad
to No wrap - in <head>
回答2:
You need to wrap it:
$( function(){ .....
} );
This will make sure the code doesn't execute until the browser has read all of your HTML. Currently you are executing the code before any elements with .social
are defined.
回答3:
Have you tried that code with another editor / browser locally? Maybe DW is not loading jQuery properly. Have you pasted the code to a plain text file and tested the page in a browser?
回答4:
Your problem is basic jQuery 101.... the elements don't exist when your code is firing.
Wrap code in document.ready
, or place code after the elements it refers to
API Reference: http://api.jquery.com/ready/
Also worth reading How jQuery Works in docs for better explanation.
Edit The reson code works in jsfiddle is due to dropdown in top left that says onLoad
. fiddle automatically wraps code in a load handler when that is selected
回答5:
That is just idle scripting.
$(document).ready(function(e) {
$(".social").hover(function() {
$("h1", this).hide();
$(".networks", this).fadeIn();
}, function() {
$(".networks", this).hide();
$("h1", this).fadeIn();
});
});
This line $(document).ready(function(e) {
makes it start onLoad through the scripting.
This is what your the code does. http://jsfiddle.net/3SKqQ/
来源:https://stackoverflow.com/questions/15192882/jquery-show-and-hide-doesnt-work-something-is-missing-and-i-cant-figure-it-out