JavaScript:如果未定义,则实现'element.hasAttribute'[对于IE7]

sla*_*oah 4 html javascript dom extend internet-explorer-7

我需要创建一个与IE7兼容的exisitng Web应用程序.

代码element.hasAttribute广泛使用,IE7与此方法有问题.

对象不支持属性或方法'hasattribute'

我试图检查代码是否一个input元素hasAttribute定义了方法,如果没有,我试图将它添加到所有input元素.

//create an input element variable << works fine
var myInput = document.createElement("input");

//see if it has the 'hasAttribute' method << condition works fine
if (('hasAttribute' in myInput)==false)
{

    //get all input elements into objInputElements <<works fine
    var objInputElements=document.getElementsByTagName("input");

    // MORE CODE NEEDED - To implement a hasAttribute function for all 
    // elements in the array probably using something
    // like: !!element[attributeName] which works in IE7. See link and notes below.
}
Run Code Online (Sandbox Code Playgroud)

本文介绍如何定义单独的函数来执行此操作.但是,hasattribute如果没有定义,我想将方法添加到元素中.(这样我就不需要更改当前编写的所有代码)

重要说明:表单中有> 1000个隐藏输入字段,因此需要以非常有效的方式将"hasattribute"方法添加到元素中.

请告诉我如何实现这一目标.谢谢!

Bre*_*mir 6

由于Element.prototype不支持IE <8,因此没有有效的polyfill方法hasAttribute.低效的方式(如果你想避免填充)将是这样的(在所有输入加载后放置):

<input data-abc="" />
<script>

if (!window.Element || !window.Element.prototype || !window.Element.prototype.hasAttribute) {

(function () {
    function hasAttribute (attrName) {
        return typeof this[attrName] !== 'undefined'; // You may also be able to check getAttribute() against null, though it is possible this could cause problems for any older browsers (if any) which followed the old DOM3 way of returning the empty string for an empty string (yet did not possess hasAttribute as per our checks above). See https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute
    }
    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].hasAttribute = hasAttribute;
    }
}());

}

var inputs = document.getElementsByTagName('input');
document.write(
    'has?' + inputs[0].hasAttribute('abc') // false
);
document.write(
    'has?' + inputs[0].hasAttribute('data-abc') // true
);

</script>
Run Code Online (Sandbox Code Playgroud)