[英]How do I use javascript for html?
I'm a beginner of Javascript and html. 我是Javascript和html的初学者。 I want to output 10 "Hi" but following code doesn't work.
我想输出10“嗨”,但以下代码不起作用。 What should I do?
我该怎么办?
index.html and app.js is in a same folder. index.html和app.js位于同一个文件夹中。
index.html 的index.html
<html>
<head>
</head>
<body>
<div class = "test"></div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js app.js
var main = function(){
for(var i = 0; i<10; i++){
var f = document.createElement('p');
f.innerText = "Hi.";
var div = document.getElementByClass('test');
div.appendChild(f);
};
$(document).ready(main);
$
being undefined and thus a reference error $
undefined的错误,从而导致参考错误 $
(which you probably want to do by including the jQuery library ) $
(您可能希望通过包含jQuery库来实现 ) Alternatively, just get rid of $(document).ready(main);
或者,只需摆脱
$(document).ready(main);
and call main()
directly instead. 并直接调用
main()
。 You don't appear to have any need for jQuery in there. 你似乎没有任何jQuery需求。
You'll then have to contend with getElementByClass
not being a function. 然后你必须与
getElementByClass
竞争不是一个函数。 See getElementsByClassName
or querySelector
instead. 请参阅
getElementsByClassName
或querySelector
。
first of all you are referencing jQuery library without including it 首先,你要引用jQuery库而不包括它
$(document).ready(main);
add the link to jquery library: 添加到jquery库的链接:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
then your script has some errors: 然后你的脚本有一些错误:
try to use the developer console of your browser to debug it 尝试使用浏览器的开发人员控制台进行调试
your code should look like this: 您的代码应如下所示:
var main = function(){
/*no need to exec this for all loops iteration
and the right method is getElementByClassName not getElementByClass */
var div = document.getElementByClassName('test')[0];
for(var i = 0; i<10; i++){
var f = document.createElement('p');
f.innerText = "Hi.";
div.appendChild(f);
};
} /*you forgot to close the function*/
$(document).ready(main);
(function () {
for (var i = 0; i < 10; i++) {
var f = document.createElement('p'),
div = document.querySelector('.test');
f.innerText = 'Hi';
div.appendChild(f);
}
})();
Several things: 几件事:
}
}
getElementsByClassName
, not getElementByClass
getElementsByClassName
,而不是getElementByClass
$(function () { for (var i = 0; i < 10; i++) { var f = document.createElement('p'); f.innerText = "Hi."; var div = document.getElementById('test'); div.appendChild(f); } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.