Today is Friday, very free. There is nothing to do while sitting in front of the computer. People in the product line did not mention any new requirements. There may be new requirements and work arrangements next week, but that is next week. Today I want to write something technical, just as taking notes. My level is limited. I hope everyone can give me some advice and be merciful, haha.
Sometimes we want to extend the functionality of DOM elements and add some custom methods to make it more flexible and convenient to use; let’s take an example first:
< head>
DOM function extension
Hello
There is no doubt that as can be seen from the above code, when you click on the A tag, "Hello" will pop up. tagA is a DOM element, except for onclick In addition to events, there are onmouseover, onmouseout, onmousemove, etc., and these events are all inherent in the DOM element itself; but now we want to extend it, for example, to make it support tagA.bind, I can use tagA.bind( "click",function(){}), instead of tagA.onclick=function(){}. OK, the purpose is very clear now. Let’s look at the following code first:
DOM function extension Hello
The above This piece of code is the final result after the function is expanded. It has the same function as the previous piece of code, but it cannot be executed now. It needs to be extended. Before that, let’s take a look at some basic knowledge. This is very important. Because we will use it later:
1. HTMLElement. In the DOM standard, each element inherits from HTMLElement, and HTMLElement inherits from Element, and Element inherits from Node; so we can use the prototype of HTMLElement to extend HTML. How to implement the methods and attributes of elements? Let’s look at a piece of code:
DOM function extension
!--
HTMLElement.prototype.Alert=function(){
alert("This is an extension method");
}
var tagA=document.getElementById("tagA");
tagA.Alert();
//-->
The above code will pop up "This is an extension method" when the page is loaded. However, I believe you have noticed that it will error in IE6, 7, and 8, but it will not work in IE9 or above or in browsers such as Chrome, Firefox, and Opera. Everything runs normally inside. This is a compatibility issue. Don't worry, it will be solved later.
The above code is not flexible enough. Let’s optimize it to make it more flexible:
DOM function extension
Hello
Hello < ;script type="text/javascript">