开发者

ie, javascript and 'item' as a variable name

Is this considered to be a JS bug in IE?

Please check the following function

function select_deselect_all_items(status)
    {
        select_deselect_items_under_panel(status, $('myPanel'));

        panel = $('myPanel');
        var items = panel.getElementsByTagName('input');
        for (var n = 0; n < items.length; n++) {
      开发者_StackOverflow中文版      item = items[n];
            if (item.id.substr(0, 10) == 'myItems_') {
                item.checked = status;
                select_deselect_items_under_panel(status, $('myPanel'));
            }
        }
    }

Now, this works fine in FF and Chrome, but generate an error in IE. Error is the following:

Error: Unable to get value of the property 'substr': object is null or undefined

I have this function in several places throughout my code (haven't placed it into one js file, unfortunately) and I've already stumbled on this issue. The problem seems to be with item variable. If this is changed to something else, i.e. myWildVarName, things seem to work ok. I debugged the page in IE, and I see that item is an object with certain properties...

So, a bug or a rookie mistake?

Cheers


You do have a mistake in your code, in that you never declare the item variable and thus fall prey to the Horror of Implicit Globals.

My guess is that you have something on your page that has either the name or id "item", and so that's becoming a property of window because IE does that (and many other browsers have followed suit). As you probably know, properties of window are globals, and so when you try to assign to the item symbol in your function, you're assigning to that global property. Depending on what item is, IE may be trying to apply "don't actually assign to the object, but assign to its default property instead" logic (because it's allowed to do that if it wants to with host objects) and running into an issue.

Declare your local variable (always a good idea) and the problem should go away.


Update: Now that you've posted the actual error, the rationale above for what's happening may not be spot-on, on but the recommendation (declare the local) remains the same. :-)


IE and some other browsers have the habit of adding a reference in the global scope for each element that has an id, so the likely reason for item to already have a value in IE is that you have an element with id="item".

If you declare the item variable as a local variable in the function, it's not a problem that it exists in the global scope also:

var item;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜