[英]Javascript OOP, does not give me an error yet code does not work
+ function Engine() {
var createObject = function(elemClass, height, width){
this.element = document.createElement('div');
$(this.element).addClass(elemClass)
$(this.element).css('height', height);
$(this.element).css('width', width);
};
var box1 = new createObject('box', 200, 400);
$('body').append(box1.element);
}();
Why does the following code provide no error? 为什么以下代码不提供错误? yet it also does not create the div within the body tag.
但它也不会在body标签中创建div。 Lets assume the body is empty.
让我们假设身体是空的。 Any help will be greatly appreciated.
任何帮助将不胜感激。
Thanks, 谢谢,
Why does the following code provide no error?
为什么以下代码不提供错误?
Three possible reasons: The code didn't run, there is no error, or you did not see it. 三个可能的原因:代码没有运行,没有错误,或者你没有看到它。 I'd guess the second.
我猜第二个。
yet it also does not create the div within the body tag.
但它也不会在body标签中创建div。
Maybe because there is no <body>
element which could match your selector at the time the code runs . 也许是因为在代码运行时没有
<body>
元素可以匹配您的选择器。 $('body')
can be an empty collection and jQuery does not grump about it. $('body')
可以是一个空集合,jQuery也不会对它产生影响。
Have a look at Why does jQuery or a DOM method such as getElementById not find the element? 看看为什么jQuery或像getElementById这样的DOM方法找不到元素? for exact reason and some solutions, the easiest of which will be using
jQuery()
: 由于确切的原因和一些解决方案,最简单的将使用
jQuery()
:
$(function Engine() {
…
$('body').append(box1.element);
});
It depend on where in the page you put your script code. 它取决于您放置脚本代码的页面中的位置。
if it is inside the body
element, then the document already contains a body element, $('body')
return it and all work fine. 如果它在
body
元素内,那么文档已经包含一个body元素, $('body')
返回它并且所有工作正常。
if it is in head
element, the body does not exists yet at the time your script run, $('body')
return an empty collection, and are appending the div into nothing. 如果它在
head
元素中,则在脚本运行时,body仍然不存在, $('body')
返回一个空集合,并将div附加到任何内容中。
You get no errors because jquery does not throw an error i this case. 你得到没有错误,因为在这种情况下jquery不会抛出错误。
If you want to write the script inside head element, wrap it in a document.ready call: 如果要在head元素内编写脚本,请将其包装在document.ready调用中:
<script>
+ function Engine() {
$(document).ready(function(){
var createObject = function(elemClass, height, width){
this.element = document.createElement('div');
$(this.element).addClass(elemClass)
$(this.element).css('height', height);
$(this.element).css('width', width);
};
var box1 = new createObject('box', 200, 400);
$('body').append(box1.element);
});
}();
</script>
and it will work. 它会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.