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

Strange setAttribute behavior in IE8 after Object extend

本文关键字:setAttribute 行为 对象 扩展 IE8      更新时间:2023-09-26

我用下面的代码来创建一个微库(类似于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">)。我该如何解决这个问题?

注意:我正在使用IE8开发人员工具(F12)的"HTML"选项卡来验证这一点。

与其将attr()函数附加到所选元素上(IE8显然将其解释为在元素本身上设置属性),不如将其附加到Element对象的原型上。

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