Prototype - addMethods() 方法

此方法可以将您自己的方法混合到 Element 对象中,以后您可以将其用作扩展元素的方法。

要添加新方法,只需将方法哈希提供给 Element.addMethods。请注意,每个方法的第一个参数必须是一个元素。

语法

element.addMethods([hash of methods]);

或

element.addMethods(tagName, methods);

此处,该方法的第二种形式将使添加的方法仅适用于特定标签。

返回值

无。

示例

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         // 使所有元素都可以使用 changeColor 方法
         Element.addMethods({
            changeColor: function(element, colorName) {
               element = $(element);
               element.style.color = colorName;
               return element;
            }
         });
         function ShowEffect() {
            node = $("firstDiv");
         
            // 现在调用 changeColor 方法
            node.changeColor( "red" );
         }
      </script>
   </head>
   
   <body>
      <div id = "firstDiv">
         <p>This is first paragraph</p> 
      </div>
      <br />
      
      <input type = "button" value = "ShowEffect" onclick = "ShowEffect();"/>
   </body>
</html>

输出

prototype_element_object.html