无法设置属性'href'未定义或空引用的

Exception Unable to set property 'href' of undefined or null reference when

本文关键字:引用 未定义 href 设置 属性      更新时间:2023-09-26

问题是这样的:我试图动态地改变在body - onload中执行的函数CheckCookie中的innerHTML和链接的href。下面是函数:

function checkCookie()
{
    var username = getCookie("username");
    if (username != null && username != "")
    {       
        document.getElementById("firstlink").href = "http://localhost:8080/newLogIN/probalassfinalwithoutstyle.html";
        document.getElementById("firstlink").innerHTML = "Go to my lesson";       
    }
}

我还有另一个jquery函数在document ready

上执行
function DropDown(el) {
    this.dd = el;
    this.initEvents();
}
DropDown.prototype = {
    initEvents: function() {
        var obj = this;
        obj.dd.on('click', function(event) {
            $(this).toggleClass('active');
            event.stopPropagation();
        });
    }
}

$(function() {
    var dd = new DropDown($('#dd'));
    $(document).click(function() {
        // all dropdowns
        $('.wrapper-dropdown-3').removeClass('active');
    });
});

在我的身体里我有这个

<body onload="CheckCookie()">
    <div id="dd" class="wrapper-dropdown-3">LoGG
        <ul class="dropdown">
            <li><a href="#" id="firstlink">Gismo Account</a> </li>
    </div>
</body>

一切都如我所愿,但当我添加

document.getElementById("dd").innerHTML = "Hi," + getCookie("username");  

改变dddiv的InnerHtML它给了我一个异常

SCRIPT5007:无法设置未定义或空引用的属性'href'

当您运行document.getElementById("dd").innerHTML = "Hi," + getCookie("username");时,您正在完全替换dd元素的内容。这包括firstlink锚。因此,当您要更改该链接时,没有具有该ID的元素,因此它会失败并出现该错误。