+ 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);
}();
为什么下面的代码没有报错?但它也不会在 body 标签内创建 div。假设 body 是空的。任何帮助将不胜感激。
谢谢
最佳答案
这取决于您在页面中放置脚本代码的位置。
如果它位于 body
元素内,则文档已包含
一个 body 元素,$('body')
返回它并且一切正常。
如果它位于 head
元素中,则在脚本运行时主体尚不存在,
$('body')
返回一个空集合,并且将 div 附加到任何内容中。
你不会得到任何错误,因为在这种情况下 jquery 不会抛出错误。
如果您想在 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>
它会起作用。
关于Javascript OOP,不会给我错误,但代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21319335/