对象扩展后IE8中的奇怪setAttribute行为

时间:2015-05-27 01:43:57

标签: javascript internet-explorer-8

我有以下代码用于创建各种微型库(类似于JQuery,但只有我需要的东西)。

window.$ = function(selector, context, undefined) 
{
    var getSelectorTest = function(selector, context, undefined)
    {
        var el;
        var selector_key = selector.slice(0, 1),
            matches = {
                '#': 'getElementById',
                '.': 'getElementsByClassName',
                '@': 'getElementsByName',
                '=': 'getElementsByTagName',
                '*': 'querySelectorAll'
            }[selector_key],
            selector_value = selector.slice(1);

        //add fallback for getElementsByClassName is not supported e.g. IE8
        if(matches === 'getElementsByClassName' && !document.getElementsByClassName)
        {
            matches = 'querySelectorAll';
            selector_value = selector;
        }

        // now pass the selector without the key/first character
        el = (((context === undefined) ? document: context)[matches](selector_value));
        return el;
    };

    var elem = getSelectorTest(selector, context, undefined);

    //Extend elem before returning it
    elem.attr = function(name, value) {
    if(value)
    {
        this.setAttribute(name, value);
        return this;
    }
    else
    {
        return this.getAttribute(name);
    }   

    return elem;
};

然后当我运行以下代码时:

<script>
    domReady(function(){ //https://github.com/cms/domready
        var el_1 = $('#container-1');
        el_1.attr("data-test", "random_value");
    });
</script>

使用IE8时我得到以下信息:

<div id="container-1" attr="function(name, value) {
            if(value)
                {
                    this.setAttribute(name, value);
                    return this;
                }
                else
                {
                    return this.getAttribute(name);
                }

        }" data-test="random_value">

当然,当我使用Chrome和Firefox时,情况并非如此(我得到预期的输出,即<div id="container-1" data-test="random_value">)。我该如何解决这个问题?

注意:我正在使用&#39; HTML&#39; IE8开发者工具(F12)的选项卡来验证这一点。

1 个答案:

答案 0 :(得分:0)

不是将attr()函数附加到所选元素(IE8显然将其解释为在元素本身上设置属性),您可能会更好地将其附加到Element对象的原型。

Element.prototype.attr = function(name,value){ ...