سؤال

I created two JavaScript functions.

var a, b;

function changeTo(a, b) {
    document.getElementById(a).className = 'editborder';
    document.getElementById(b).className = 'editborder';
}
function changeToo(a, b) {
    document.getElementById(a).className = 'editborder_';
    document.getElementById(b).className = 'editborder_';
}

They are called by the <asp:LinkButton> with one argument:

<asp:LinkButton ID="LinkButton7" runat="server" 
    onMouseover="changeTo('div_master');" 
    onMouseout="changeToo('div_master');" 
    Text="Edit Bg Color" CommandArgument="0" OnClick="lnkchangebg_click">
</asp:LinkButton>

It works fine in Chrome, but in IE6 it causes the following error:

error 'document.getelementbyid(...)' is null or not an object

How is this caused and how can I solve it?

هل كانت مفيدة؟

المحلول

Your function gets two required parameters and you're passing just one.

You could refactor your functions so the second parameter wont be required, like this:

function changeToo(a, b) {
    document.getElementById(a).className = 'editborder_';
    if (typeof b !== "undefined") {
        document.getElementById(b).className = 'editborder_';
    }
}

It also seems a bit clunky to use two different functions that seem to do almost exactly the same. If you would take it one step further, you could refactor your whole code to this:

function changeClass(a, strClass) {
    if (typeof a === "string") {
        document.getElementById(a).className = strClass;
    } else if (typeof a === "object" && a.length > 0) {
        for (var id in a) {
            if (a.hasOwnProperty(id)) {
                document.getElementById(id).className = strClass;
            }
        }
    } else {
        throw new Error("Invalid argument supplied in changeClass().");
    }
}

Now you can do:

<asp:LinkButton ID="LinkButton7" runat="server" 
    onMouseover="changeClass('div_master', 'editborder');" 
    onMouseout="changeClass('div_master', 'editborder_');" 
    Text="Edit Bg Color" CommandArgument="0" OnClick="lnkchangebg_click">
</asp:LinkButton>

Or even:

<asp:LinkButton ID="LinkButton7" runat="server" 
    onMouseover="changeClass(['div_master', 'anotherElementId'], 'editborder');" 
    onMouseout="changeClass(['div_master', 'anotherElementId'], 'editborder_');" 
    Text="Edit Bg Color" CommandArgument="0" OnClick="lnkchangebg_click">
</asp:LinkButton>

If that still doesn't fix your problem, Louis Lazaris wrote an excellent post about avoiding problems with .getElementById() in Internet Explorer.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top