论坛首页 Web前端技术论坛

为prototype的Element增加两个方法

浏览 2888 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-06-22  
一下的代码是我从国外的网上看的,我又改进了一点,在这跟大家分享
document.getElementsByAttribute = function(attribute,parent) {
    return $A(($(parent) || document.body).getElementsByTagName('*')).inject([],function(elements,child){
		if(Element.readAttribute(child,attribute)!=null)
                   //这个判断我改成了!=null原来没有但这样当你在元素中只是添加了某个属性
                      //如<input type='text' required />这时原来的代码就会找不到
			elements.push(Element.extend(child));
		return elements;
	});
}



document.getElementsByAttributeValue = function(attribute,value,parent) {
	return $A(($(parent) || document.body).getElementsByTagName('*')).inject([],function(elements,child){
		if(Element.readAttribute(child,attribute) == value)
			elements.push(Element.extend(child));
		return elements;
	});
}

Element.addMethods({
	getElementsByAttribute: function(element,attribute){
		return document.getElementsByAttribute(attribute,element);
	},
	getElementsByAttributeValue: function(element,attribute,value){
		return document.getElementsByAttributeValue(attribute,value,element);
	}
});

使用时
<html>
<head>
<script src='prototype.js'></script>
<script src='prototype.tidbits.js'></script>
<script language="javascript" type="text/javascript">
    Event.observe(window,'load',function(){
        alert($('div1').getElementsByAttribute('require').length);
        alert(document.getElementsByAttribute('require').length);
    })
</script>
</head>
<body>
    <div id='div1'>
    <input type='text'   require/>
    <input type='text' require />
    </div>
</body>
</html>
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics