javascript jQuery 选择器不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21503984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:02:39  来源:igfitidea点击:

jQuery selector not working

javascriptjqueryhtml

提问by Norbertle

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.

我一直试图弄清楚为什么我的 JavaScript 代码不起作用。警报工作正常,但是当我尝试在 div 中写入时它什么也不做。我究竟做错了什么?我一直试图用谷歌搜索答案,但这并没有太大帮助。

 <!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

我的 javascript 是

$("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

-布伦特

回答by j08691

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:

您需要将 JavaScript 放在页面末尾的结束正文标记之前或头部,并包含在文档就绪调用中。前任:

$( document ).ready(function() {
    // your code here
});

jsFiddle example(placing code at end of document)

jsFiddle 示例(在文档末尾放置代码)

The way you have it now, you're trying to execute code on elements that don't yet exist.

按照您现在的方式,您正在尝试对尚不存在的元素执行代码。

回答by Rimpy

Wrap your code in document-ready handlerand assuming jquery is loaded

将您的代码包装在文档就绪处理程序中并假设已加载 jquery

$(document).ready(function() {
   $("p").append("HEY HEYH YEYEHE.");
});

回答by 0__1

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:

为了让 jQuery 正常运行,应该首先加载 html 内容。因此,您应该将代码放在文档就绪处理程序中。试试这个:

$( document ).ready(function() {
    // put your code here as it is 
});