简体   繁体   English

javascript createElement通过appendChild返回错误

[英]javascript createElement via appendChild returning error

I'm trying to write a short javascript function to add buttons for prev/next to a css-slider I've put together. 我正在尝试编写一个简短的javascript函数,以将上一个/下一个按钮添加到我放在一起的css-slider中。
I don't have access to the DOM, so figured I'd just insert the div's via javascript. 我没有访问DOM的权限,所以我想只是通过javascript插入div即可。 Here is the function: 这是函数:

function createfn(){
  var element = document.createElement("div");
  var prev = document.createTextNode("<");
  element.appendChild(prev);
  document.getElementsByClassName("sqs-gallery")[0].appendChild(element);
}
window.onload=createfn();

I am getting an error: 我收到一个错误:

"Cannot read property 'appendChild' of undefined" “无法读取未定义的属性'appendChild'”

The div container with class .sqs-gallery is definitely appearing on the page. 页面上肯定出现了类为.sqs-gallerydiv容器。 I was questioning whether this was somehow running before the DOM fully loaded, but I have the window.onload in there which (I believe) should wait until everything is loaded before running the function. 我在问这是否在DOM完全加载之前以某种方式运行,但是我在其中有window.onload (我相信)应该在所有内容加载完毕后再运行该函数。

Any and all thoughts and help is greatly appreciated! 任何想法和帮助将不胜感激!

You perform window.onload=createfn() ; 您执行window.onload=createfn() ;

it means that you assign result of createfn() to onload (not the function). 这意味着您将createfn()结果分配给onload (而不是函数)。 And function " createfn " being executed immediately (does not wait for window loading). 并且函数“ createfn ”被立即执行(不等待窗口加载)。

Just remove parentheses to assign handler instead of function value. 只需删除括号即可分配处理程序而不是函数值。

If you leave the code as window.onload=createfn() (with the parenteheses) createfn will run directly as the code starts to run (even before the DOM has loaded) because the result needs to be assigned to window.onload . 如果将代码保留为window.onload=createfn() (带有括号),则createfn将在代码开始运行时直接运行(甚至在DOM加载之前),因为需要将结果分配给window.onload

What you instead should be trying to do is assign the function, not the result: window.onload=createfn . 相反,您应该尝试分配的是函数,而不是结果: window.onload=createfn This should work just fine. 这应该很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM