0

问题是这样的:我尝试在正文中执行的函数中动态更改 LINK 的 innerHTML 和 href CheckCookie- onload。这是功能:

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 函数,它在文档就绪时执行

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");  

更改 dd div 的 InnerHtML 它给了我一个例外

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

4

1 回答 1

2

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

于 2013-05-28T08:29:02.747 回答