jQuery中的InsertAfter错误'Uncaught TypeError: Cannot set pro

InsertAfter in jQuery giving error 'Uncaught TypeError: Cannot set property 'innerHTML' of null'; Why?

本文关键字:TypeError Cannot set pro Uncaught InsertAfter 中的 错误 jQuery      更新时间:2023-09-26

基本上,我创建了一个模态,单击按钮将在模态中显示函数的结果。我希望按钮点击删除所有在初始模态,只显示结果。

就像我说的,我得到了InsertAfter in jQuery giving error 'Uncaught TypeError: Cannot set property 'innerHTML' of null';

我很困惑,因为我得到了模态容器的处理:

modal = $('.modal')

我创建了一个输出元素,像这样:

 output = doc.createElement('p');
 output.setAttribute('id', 'output');

它将被附加到模态…

 $('#output').insertAfter(modal);

那么,如果我刚刚创建了容器,为什么会得到null错误呢?

 doc.getElementById('output').innerHTML = out.join("'n");
HTML:

<script id="templateID" type="text/html">
    <div id="overlay">
        <div id="container" class="container">
            <div class="row">
                <div class="twelve columns">
                    <div class="modal">
                        <p>This app will go through some of your markup to determmine if it could be more accessible.  We will start by checking the alt tags on your images, seeing if they exist, or if the tags are empty! <br> Lets get started!<br>
                        <a id="getStartedBtn" class="button button-primary modal-button">click-me</a>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</script>

JS:

function altChecker() {
        var doc = document,
            out = [],
            getStartedBtn = doc.getElementById('getStartedBtn'),
            modal = $('.modal'),
            output = doc.createElement('p');
            output.setAttribute('id', 'output');

        EventUtility.addHandler(getStartedBtn, 'click', function() {
            var all = doc.getElementsByTagName("IMG");
            for (var i = 0, max = all.length; i < max; i++) {
                var id = all[i].id;
                if (all[i].hasAttribute('alt')) {
                    out.push('Your image element, with the id of <strong>' + id + '</strong>, has an <strong> alt </strong> tag.');
                    var value = all[i].getAttribute('alt');
                    if (value != "") {
                        out.push(id + ' alt="' + value + '"');
                    } else {
                        out.push('But <strong>' + id + '''s alt </strong> is empty');
                    }
                } else {
                    out.push(id + ' does not have alt');
                }
            }

            $('#output').insertAfter(modal);
            doc.getElementById('output').innerHTML = out.join("'n");

        });
    }

那么,如果我刚刚创建了容器,为什么会得到null错误呢?

因为你没有把它放在DOM中,所以$("#output")不会找到它,即使它有一个id;所以$("#output").insertAfter(modal);线是无操作的。之后,当您执行doc.getElementById('output')时,它不在DOM中,因此您返回null,并且它失败了。

相反,由于您已经有了对output中元素的引用,您可以这样做:

$(output).insertAfter(modal);

和以后你使用getElementById的地方,没有必要再查找它,你已经有它了,所以:

output.innerHTML = out.join("'n");

$(output).html(out.join("'n"));