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

标签 javascript html dom internet-explorer-7 extend

我需要使现有的 Web 应用程序与 IE7 兼容。

该代码广泛使用了 element.hasAttribute,而 IE7 对此方法存在问题。

Object doesn't support property or method '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.
}

This article描述了如何定义一个单独的函数来执行此操作。但是,如果未定义,我想将 hasattribute 方法添加到元素中。 (这样我就不需要更改所有当前编写的代码)

重要提示:表单中有超过 1000 个隐藏的输入字段,因此需要以非常有效的方式将“hasattribute”方法添加到元素中。

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

最佳答案

由于 Element.prototype 不支持 IE < 8,因此没有有效的方法来填充 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>

关于JavaScript:如果未定义则实现 'element.hasAttribute' [对于 IE7],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19325673/

相关文章:

javascript - 如何使用 jQuery 从 <template> 中选择元素

javascript - 打开新窗口而不关注它

javascript - 无法调用休息电话

javascript - 使用 Javascript 的随机光标图像

javascript - 如何在加载所有 Assets 之前添加加载效果?

javascript - $state.go 不适用于 angularjs 1.5

html - 即使父级设置为 100%,内部 div 也不会拉伸(stretch)到外部 div

javascript - 如何在for循环中添加DOM元素

javascript - AngularJs : what is the best way to changing DOM elements when there are "global"?

javascript - 分配 Array.prototype.indexOf 后 for...in 导致此错误的原因是什么?