问题
ive been trying to figure out why my JavaScript code will not work. The alert works fine, but when I try to write in a div it does nothing. What am I doing wrong? Ive been trying to google the answer, but that has not been too helpful.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="gamejavascript.js" type="text/javascript"> </script>
<link rel="stylesheet" type="text/css" href="gameStyle.css">
<title>Text Adventure RPG</title>
</head>
<body>
<p>hey </p>
<div id="eventWindow">
<div id="title">Black Forest</div>
<div id="eventContent">You have entered the black forest. Lucky you!</div>
</div>
<div id="itemList">Hey hey hey </div>
<div id="userStat"> </div>
</body>
</html>
My javascript is
$("p").append("HEY HEYH YEYEHE.");
alert("You madam are a horse!");
$("#userStat").html("Hey baby");
/* var user = function(attack,health)
{
this.attack = attack;
this.health = health;
};
var player = new user(10,100); */
thank you so much for your help!
-Brent
回答1:
You need to put your JavaScript at the end of the page before the closing body tag or in the head and wrapped in a document ready call. Ex:
$( document ).ready(function() {
// your code here
});
jsFiddle example (placing code at end of document)
The way you have it now, you're trying to execute code on elements that don't yet exist.
回答2:
Wrap your code in document-ready handler and assuming jquery is loaded
$(document).ready(function() {
$("p").append("HEY HEYH YEYEHE.");
});
回答3:
In order jQuery to run properly, the html content should be loaded first. For this reason you should put your code in the document ready handler. Try this:
$( document ).ready(function() {
// put your code here as it is
});
来源:https://stackoverflow.com/questions/21503984/jquery-selector-not-working