Monday Topic 4 (a comprehensive summary of JavaScript, Dom, and jQuery & lt; Dom & gt ;)

Source: Internet
Author: User

--> Directory Navigation 1. Exploring Dom 1. dom Introduction 2. Dom basics 1. window top-level object 2. body, document Object event 3. common HTML element events 4. bubble event 5. this and event. srcElement 3. Dom operation 1. dynamically create Dom 2. innerText, innerHTML 4. form object 5. regular Expression in JS 6. firefox (FF) incompatibility: 7. performance Optimization 4. Strength Detection 1. Dom JavaScript-> Dom, C #->. net Framework; JavaScript and C # are some basic syntaxes without Dom and. net class library, JavaScript and C # cannot exert its power. This article will take you back to Dom operations. 1. dom introduces Dom (document tags are processed as objects) (1) DOM is an html page model. Each tag is used as an object, by calling the attributes and methods in the DOM, javascript can program and control the text box, layer, and other elements in the webpage. (2) DOM is some classes and functions that allow JavaScript to operate Html page controls (3) DHtml = CSS + JavaScript + Dom dynamic setting event <script type = "text/javascript"> function F1 () {alert ('in f1 ');} </script> <input type = "button" value = "associate F1" onclick = "document. onclick = F1; "/> <input type =" button "value =" associate F1 "onclick =" F1 () "with () indicates that a function is called, directly write the function name to set it as the event handler. Ii. Dom basics 1. window top-level object (1) window method ① when calling the window method, you can omit the window ② method alert: pop-up warning dialog box confirm: OK, cancel dialog box setInterval (code, delay ): start the timer. We recommend that you use the anonymous clearInterval (intervalId): stop the timer setTimeOut (): scheduled to run the specified code at intervals. Only one clearTimeOut () is executed (): clear the attribute ① window of the scheduled window (2. location Property: location. protocol: This property stores the protocol section of the URL. Location. hostname: This property stores the Host Name of the URL. Location. port: This property saves the port number section in the URL. Location. pathname: This property stores the file name section in the URL. Location. search: saves the URL query section (if any ). Location. hash: saves the anchor name in the URL (if any ). Method: window. location. href: Obtain the current address window. location. reload (): refresh the current page ② window. event-> press the key, composite key altKey, shiftKey, ctrlKey if (window. event. altKey) {alert ("Alt key pressed");} which buttons are pressed (different from the ASCII value) keyCode-> use the mouse coordinates clientX and clientY to obtain the mouse coordinates, relative to the page, offsetX and offsetY are the offset coordinates screenX and screenY of the current element in the upper left corner of the current element.-> stop the event and continue the window execution. event. return = false; (standard) Firefox can also use return false; To set the return value of the current event handler to false ③ window. screen windo W. screen. width: obtains the user's screen resolution width window. screen. height get user Screen Resolution height ④ clipboardData setData () set clipboard value getData () read clipboard value clearData () Clear clipboard value function Setclipboard () {window. clipboardData. setData ('text', window. clipboardData. getData ('text') + 'all rights reserved for thunder');} ⑤ history (operation history) window. history. back () back window. history. go (-1) returns window. history. forward () forward window. history. go (1) Forward ⑥ document --> write and writeln commit E Nt. write is the document that dynamically creates content and elements. writeln is also a dynamically created content, and the source code will wrap the line to add: the above two will only be used when loading the page to ensure that the content application on the page: Ad link, modify the js code on the server side and modify all the other references --> get the dom object getElementById () and get the object getElementsByName () based on the element Id () get the object getElementsByTagName Based on the element name and get the object copy code function GetDomObject () {alert ('getelementbyid: '+ document. getElementById ('txtelementbyid '). value); var arrobjs = document. getElementsByName ('abc'); for (var I = 0; I <arr Objs. length; I ++) {alert ('getelementsbyname element value: '+ arrobjs [I]. value);} var tagNameObjs = document. getElementsByTagName ('P'); for (var j = 0; j <tagNameObjs. length; j ++) {alert ('getelementsbytagname element value: '+ tagNameObjs [j]. innerHTML) ;}} copy code Note: you cannot use for in (key-value pairs) loop 7. Other properties close return true or false, indicating whether the window object closes the corresponding window. Opener indicates the window object that opens the current window. Defaultstatus settings and the text content displayed by default in the return window status bar. Set Status and return the content that is currently displayed in the Status bar of the window. ScreenTop returns the vertical distance of the vertex in the upper left corner of the window on the screen. SrceenLeft returns the horizontal distance of the vertex on the screen in the upper left corner of the window. Back to navigation 2. trigger After loading the onload page of the body and document Object event: After loading the page, you can use document. getElementById ("Control Id") is used to obtain the dom element ID. After the onunload page is uninstalled, The onbeforeunload page is triggered. Note: to register an event for the entire page, use document, do not use the body to return to the navigation 3. event onclick, ondblclick, onkeydown, onkeypress, onkeyup, and onmousedown of common HTML elements) onmousemove, onmouseout, onmouseover, and onmouseup) oncontextmenu (triggered when right-click in the browser to display the "right-click menu") back to navigation 4. Bubbling event bubbling: If element A is nested in element B, not only the onclick event of Element A will be triggered, But The onclick event of Element B will also be triggered. The trigger sequence is "from the inside out ". <Table onclick = "alert ('table onclick');"> <tr onclick = "alert ('tr onclick '); "> <td onclick =" alert ('td onclick'); "> <p onclick =" alert ('P onclick '); "> aaaa </p> </td> <td> bbb </td> </tr> </table> cancel event bubble: window. event. cancelBubble = true; // return to the navigation bar under IE 5. this and event. srcElement this: indicates the control in which an event occurs. This can be used only in the event response function to obtain the Event Control. window cannot be used in the function called in the event response function. event. srcElement: The fuction method () {alert (this. value) ;}< input type = "text" onblur = "method ()"/> This is incorrect. You can use the fuction method (btn) {alert (btn. value) ;}< input type = "text" onblur = "method (this)"/> supplement: this indicates the object of the currently triggered event, indicating who is executing the event, event Control; event. srcElement is the object that triggers the event: Event bubbles. If you want to directly use this. attribute, the function cannot be called but must be a response function, and window. event. srcElement has no such restriction. 3. Dom operation 1. dynamically create Dom createElement ('element') Create the specified tag dom object appendChild (node) Add the creation element to the corresponding element removeChild (node) Delete the element replaceChild (new, old) replace element insertBefore (new, reference) insert element back to navigation 2. innerText and innerHTML (1) almost all DOM elements have the innerText and innerHTML attributes (case sensitive), which are the text representation of the content in the element tag and the HTML source code, these two attributes are readable and writable. (2) FF does not support innerText. You can use textContent (3) innerHTML to replace createElement. It is a simple, extensive, and self-reliant creation. ① when you perform a large number of node operations, the performance of using innerHTML is better than that of frequent Dom operations ② using innerTHML = ''to delete nodes may cause memory problems innerText: Only plain text can be set, even if html code is written, the html code is also encoded. innerHTML: You can set html code and plain text. 3. operation style (1) modify the style attributes of an element. When the attribute names in css are operated in JavaScript, the attribute names may be different, for example, font-size → style. fontSize; margin-top → style. marginTop // modify the border using the camper name method: dvoObj. style. change width to the background: dvoObj. style. backgroundColor width and height: dvoObj. style. width | height -- requires px. Note: Do not write div1.style. width = 80px, but div1.style. width = '80px '(2) set the element style to modify the style of an element. Instead of setting the class attribute, copy the code for the className attribute <style type = "text/css">. emptyfield {background-color: Red ;}. normal {backgro Und-color: inherit ;}</style> <script type = "text/javascript"> function check (txt) {var s = txt. value; if (s. length <= 0) {txt. className = "emptyfield"; alert ('this field is required! ');} Else {txt. className = "normal" ;}}</script> <input type = "text" onblur = "check (this) "/> <input type =" text "onblur =" check (this) "/> <input type =" text "onblur =" check (this) "/> copy the code visibility settings to hide the hidden part. form object click (), focus (), blur (); // It is equivalent to triggering the click, focus, and focus events of elements through a program. Back to Navigation 5. regular Expression in JS (1) method for creating regular expression classes var regex = new RegExp ("\ d {5}"); var regex =/\ d {5 }/; --> it is recommended to write/Expressions/is the syntax provided by JavaScript to simplify the preparation of regular expressions. The regular expressions written in/do not need to be escaped. (2) method ① Of RegExp object matches test (str) to judge whether string str matches regular expression, equivalent to IsMatch ② in C # To extract exec (str) for search matching, the returned value is the matching result (*). It is an object that contains the "complete matching result" of the first string extracted, and all "extraction groups "; it is equivalent to replacing replace () in c # With match () and matches () to return to Navigation 6. firefox (FF) incompatibility: capability Detection: if (typeof td1.innerText = 'string') {td1.innerText = txt;} else {td1.textContent = txt;} (1) cancel the event: window. event. returnValue is not compatible with FF solution: use Firefox special e. preventDefault () or return false (2) window. event. al TKey: if (event. altKey) incompatible FF solution: copy the code function BodyClickHandlerOnFF (e) {if (e. altKey) {alert ('Press alt key');} else {alert ('normal click! ') ;}< Body onclick = "BodyClickHandlerOnFF (event);"> copy the code (3). Location: window. event. clientX, ScreenX, and OffsetX are not compatible with FF solutions: arguments [0]. clientX... (4) obtain the event source object: window. event. srcElement is not compatible with FF function MyClickHandlerOnFF (e) {var obj = e.tar get; alert (obj. value) ;}< input type = "button" value = "FF event source object" onclick = "MyClickHandlerOnFF (event);"/> (5) innerText: incompatible with FF solution: textContent (6) expands FF and IE on JavaScript and CSS back to Navigation 7. performance Optimization (1) Declare the variable to assign the initial value (2) avoid declaring the global variable directly, for example, declare the global variable name, but it may be different from window. name Conflict, so global variables are generally declared in a Global Object: var itcast = {name: 'zxh', num: 10 }; Itcast. name or itcast. num can be removed from the system. (3) When writing a large number of Js code, it is inevitable that a name conflict will occur. In this case, you can avoid naming conflicts by simulating namespaces. For example: var itcast ={}; var itcast.net ={}; var itcast.net. net0405 = {name: 'zxh', sayHi = function () {}}; (4) Avoid using global variables whenever possible. (When searching for global variables, it searches for the scope of each scope layer by layer, which is time-consuming, inefficient, and name conflict.) (5) using impairment cycles or optimizing cycle conditions, do not write I <xxx. length must be replaced by a variable, I <len. Because the loop condition is executed every time, xxx. length is calculated every time. (6) Avoid using eval ("alert (10);"); or setInterval ("myFunc ();", 1000. Inefficient! (7) use native methods, such as built-in join () and reverse (). Do not write myJoin () on your own using the methods that are originally available in the browser, which has low performance. Native methods are written in c or c ++ with high performance. (8) try to use a switch instead of multiple if-else (9) statements. var arr = [1, 2, 'A', true]; var p1 = {name: 'zxh', age: 18}; // create an object (10) use document fragments when operating a large number of dom elements to avoid multiple page updates. Var fragment = document. createDocumentFragment (); 4. Strength Testing the following are some exercises (test Source: Chuanzhi podcast). How many exercises can you do? (1) title bar with a highlighted color --> browser title text scrolling to the left and right (2) Click a button and the clicked button will display "Whining", and other buttons will display "Haha" (3) after 10 seconds, you can click the register button in the protocol text box, and the clock is counted down. (4) Addition calculator. Enter a number in the two text boxes and click the = button to place the added result to the third text box. (5) click the button to dynamically Add a website list, which is divided into two columns. The first column is the website name, the second column is the website name with a website hyperlink. Add three common websites. (6) Implement refreshing comments (7) create three input text boxes. When the cursor leaves the text box, if the text box is blank, set the background color of the text box to red, if it is not empty, it is the white (8) scoring control V1, which uses a single row of five columns as the scoring control, listens to the click event of td, When you click a td, change the background of the td to red, and the background of the td to the single-choice effect of the white (9) hyperlink --> several hyperlinks on the page, when you click a hyperlink s, the clicked hyperlink changes to a red background. Other hyperlink backgrounds do not change (10). click the button to change the color of the Table Line: even numbers act as yellow backgrounds, the default color (11) for odd-number actions is a number of text boxes. The yellow background of the text box with the focus is displayed. The background color of other controls is white (12). Click the table row, highlight the clicked line (the background is yellow), and the other lines are white background (13). Follow the mouse to fly the picture (14). Click the [Login] button, A layer (15) that displays user names and passwords is displayed. Click a thumbnail. A large image corresponding to the thumbnail is displayed at the click position, and the name, height, and other information are displayed. Click the close button in the layer to close the layer (16) the page contains a list of several team names. Place the mouse over the team name and the team name becomes a red background. The background color of other teams is white, when you click a team, the team that you click will be changed to fontSize = 30 font (17) to display the digital clock. The time is displayed in a div (18) with a search text box, if the focus is not in the text box, if there is no value in the text box, the text box displays the "Enter search keyword" in the Gray text (Gray); otherwise, the value entered by the user is displayed; when the focus is in the text box, if "Enter search keyword" is displayed, the value of the text box is cleared, and the text is changed to the security level of the Black (19) password, and the password strength is displayed (20) select all the songs (CheckBox + Label), select none, and select inverse (21) to implement the provincial/municipal selection interface. Please select the province processing, delete (22) from the back to the right Select page, select, recall, select all, all recall (23) Baidu search Automatic completion Function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.