简体   繁体   English

为什么我刚刚创建的 DOM 元素不存在?

[英]Why would a DOM element not exist when I've just created it?

The following javascript is run onload:下面的 javascript 是 onload 运行的:

var shop_checkout = {
    setup: function() {
        var img = document.createElement('img');
        img.src = '/public/styles/images/confirm_payment.png';
        img.id  = 'confirm_payment';
        img.alt = 'Confirm Payment: submit order and charge my card';
        var span = app.get('submit_checkout');
        console.log('found the span');
        span.innerHTML = '';
        console.log('emptied the span');
        span.appendChild(img);
        console.log('appended the image');
        img.onclick = shop_checkout.onsubmit;
        console.log('set the onclick');
    },
    onsubmit: function() {
        // irrelevant
    },
    submitted: function() {
        // irrelevant
    },
    oncheckout: function(json, status) {
        // irrelevant
    }
};

app.onload(shop_checkout.setup);

( app.onload() is a simple function which builds up a list of functions to fire on load, and app.get() is a simple shortcut for document.getElementById() . This is shown at the bottom.) app.onload()是一个简单的 function,它构建了一个加载时触发的函数列表,而app.get()document.getElementById() () 的一个简单快捷方式。这显示在底部。)

Most of the time, this works grand.大多数时候,这很有效。 Now and again, it gets as far as emptying the span, but fails to append the image.一次又一次,它尽可能清空跨度,但无法 append 图像。 The error message produced is: “Uncaught Error: NotFoundError: DOM Exception 8”.产生的错误信息是:“Uncaught Error: NotFoundError: DOM Exception 8”。

Now, DOM Exception 8 is a not found error, which suggests that the img doesn't exist, even though I created it just a couple of lines previously.现在, DOM 异常 8是一个未找到的错误,这表明img不存在,即使我之前只创建了几行。 What could be going on here?这里会发生什么?

I'm guessing that the img DOM element doesn't necessarily exist, even though the variable referring to it does exist.我猜测img DOM 元素不一定存在,即使引用它的变量确实存在。 Is that right?是对的吗? And what can I do about it?我能做些什么呢?

Here's the app code:这是应用程序代码:

var app = {
    get: function(id) {
        return document.getElementById(id);
    },
    onload: function(func) {
        // http://www.dustindiaz.com/top-ten-javascript/
        var oldonload = window.onload;
        if (typeof window.onload !== 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                if (oldonload) {
                    oldonload();
                }
                func();
            };
        }
    }
};

It looks like your <span> element never gets attached to the DOM. 看来您的<span>元素永远不会附加到DOM。 You can only find things by id if they descend from the document ( <html> ). 如果事物来自文档( <html> ),则只能通过id查找事物。

Make sure to append the <span> to the document before you try to find anything that gets attached to it (directly or to descendants). 在尝试查找附在文档上的任何内容(直接或后代)之前,请确保将<span>附加到文档上。

One reason is related to elements that have asynchronous data.一个原因与具有异步数据的元素有关。 Or elements that are added to the DOM after the document is loaded.或者在加载文档后添加到 DOM 的元素。 In jQuery, the following command can be used在jQuery中,可以使用如下命令

$ ('element').ready (readyFn);

https://learn.jquery.com/using-jquery-core/document-ready/ https://learn.jquery.com/using-jquery-core/document-ready/

And in Angular, element change event can be useful而在 Angular 中,element change 事件会很有用

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

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