Posted on 2007-09-05 10:46
tearofmoscow 閱讀(296)
評論(0) 編輯 收藏
一下的代碼是我從國外的網上看的,我又改進了一點,在這跟大家分享
代碼
為prototype的Element增加兩個方法
- document.getElementsByAttribute = function(attribute,parent) {
- return $A(($(parent) || document.body).getElementsByTagName('*')).inject([],function(elements,child){
- if(Element.readAttribute(child,attribute)!=null)
-
-
- 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>