Catalog
- jQuery Knowledge Carding 20190 817
jQuery Knowledge Carding 20190 817
1. Characteristics of jQuery
- Powerful selector: easy and fast to find DOM elements
- Implicit traversal (iteration): Operating multiple elements at a time
- Reading and Writing in One: Reading/Writing Data Uses a Function
- Chain invocation: methods of jQuery objects can be invoked continuously through.
- event processing
- DOM Operation (CUD)
- Style operation
- animation
- Browser Compatibility
2. Two sharp tools of jQuery
2.1 jQuery Core Function
Abbreviation: jQuery function ($/jQuery)
The direct exposure of jQuery libraries is $/ jQuery
When the jQuery library is introduced, you can use $directly.
- When the function is used: $(xxx)
- When the object is used: $. xxx()
2.2 jQuery Core Objects
Abbreviation: jQuery object
Get the jQuery object: Executing the jQuery function returns the jQuery object
Use jQuery objects: $obj.xxx()
console.log(typeof $) //$is a function console.log($ === jQuery) //true $is equivalent to jQuery console.log($ === window.$) //true $is a global function console.log(typeof $()) //The object is the jQuery object $('button').click(function () { alert(this.innerHTML) })
3. jQuery Core Function Explanation
JQuery core function, first as a function, can be used as a normal function call, according to different parameter types to derive different ways of use. Secondly, functions are also objects, that is to say, jQuery core functions can also be used as objects.
- As a general function call: $(param)
1. Parameters are functions: When DOM is loaded, this callback function is executed
2. The parameter is the selector string: Find all matching tags and encapsulate them as jQuery objects
3. Parameters are DOM objects: encapsulate DOM objects as jQuery objects
4. The parameter is html tag string (less used): create tag object and encapsulate it as jQuery object - Use as an object: $. xxx()
1. $. each (): Implicit traversal array
2. $. trim (): Remove spaces at both ends
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>03_jQuery Core function</title> </head> <body> <div> <button id="btn">test</button><br/> <input type="text" name="msg1"/><br/> <input type="text" name="msg2"/><br/> </div> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> /* Requirement 1. Click on the button: Display the text of the button, and display a new input box. Requirement 2. Traverse all element values in the output array Requirement 3. Remove the spaces at both ends of my atguigu */ /*Requirement 1. Click on the button: Display the text of the button, and display a new input box.*/ //1. Parameters are functions: When DOM is loaded, the function callback function is executed. $(function () { //2. The parameter is a selector string: Find all matching tags and encapsulate them as jQuery objects var $btn = $("#btn") $btn.click(function () { //Display button text //this is the dom element object (button) where the event occurs. //3. Parameters are DOM objects: encapsulate DOM objects as jQuery objects var text = $(this).html() alert(text) //Display a new input box //4. The parameter is html tag string (less used): create tag object and encapsulate it as jQuery object $('<input type="text" name="msg3" /><br />').appendTo('div') }) }) /*Requirement 2. Traverse all element values in the output array*/ var arr = [123, 'atguigu', true] // 1. $. each (): Implicit traversal array $.each(arr, function (index, item) { console.log('The first' + (index + 1) + 'The value of each element is' + item) }) /*Requirement 3. Remove the spaces at both ends of my atguigu*/ var str = " my atguigu " // 2. $. trim (): Remove spaces at both ends console.log(str.trim() === 'my atguigu') console.log($.trim(str) === 'my atguigu') //true </script> </body> </html>
4. jQuery Core Object Details
Execution of the jQuery function returns a jQuery object, which is a pseudo-array object containing all matching multiple dom elements.
- The basic behavior of jQuery:
- size()/length: Number of DOM elements included
- [index]/get(index): Get the DOM element of the corresponding location
- each(): Traverses through all DOM elements contained
- index(): Gets subscripts in all sibling elements.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>04_jQuery object</title> </head> <body> <button>Test 1</button> <button>Test 2</button> <button id="btn3">Test 3</button> <button>Test 4</button> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { var $btns = $('button') console.log($btns) // Requirement 1. Statistics of how many buttons there are /*size()/length: Number of DOM elements included*/ console.log($btns.size(), $btns.length) // 4 4 // Requirement 2. Remove the text of the second button /*[index]/get(index): Get the DOM element of the corresponding position*/ console.log($btns[1].innerHTML, $btns.get(1).innerHTML) // Test 2 Test 2 // Requirement 3. Output the text of all button Tags /*each(): Traversing through all DOM elements contained*/ $btns.each(function(index, domEle){ console.log(index, domEle.innerHTML, this) // this refers to each dom object }) $btns.each(function () { console.log(this.innerHTML) // Test 1, Test 2, Test 3, Test 4 }) // Requirement 4. Output'Test Three'button is the number of all buttons /*index(): Get the subscript in the sibling element*/ console.log($('#btn3').index()) // 2 }) </script> </body> </html>
- Customize a pseudoarray
/** * 1. Pseudo Array * Object object * length attribute * Numeric subscript attributes * There is no special method for arrays: forEach () push () pop () splice () */ console.log($btns instanceof Array) // false // Customize a pseudoarray var weiArr = {}; weiArr.length = 0; weiArr[0] = 'atguigu'; weiArr.length = 1; weiArr[1] = 123; weiArr.length = 2; for (var i = 0; i < weiArr.length; i++) { var obj = weiArr[i]; console.log(i, obj); // 1 123 } console.log(weiArr.forEach, $btns.forEach); // undefined undefined
5. Selector
The selector itself is just a string with specific grammatical rules, and it is of no real use. Its basic grammar rules are based on the selector grammar of CSS and are extended. The function of $(selector) is to find an array of all matching tags in the entire document according to selector rules and return them as jQuery objects.
5.1 Selector Classification
- Basic selector
- #id
- element -- element selector
- .class
- *
- Selector 1, selector 2, selector N - - Union set
- Selector 1 selector 2 selector N - - - intersection
- Hierarchical selector
- ancestor descendant descendant descendant selector
- Parent > child parent-child selector
- prev + next matches all next elements immediately after the prev element
- Pre-siblings Brother Selector
- Filter selector
- Basic filter selector
- Content filter selector
- Visibility filter selector
- Attribute filter selector
- Form selector
5.2 Basic filter selector
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>05_Basic selector</title> </head> <body> <div id="div1" class="box">div1(class="box")</div> <div id="div2" class="box">div2(class="box")</div> <div id="div3">div3</div> <span class="box">span(class="box")</span><br> <ul> <li>AAAAA</li> <li title="hello">BBBBB(title="hello")</li> <li class="box">CCCCC(class="box")</li> <li title="hello">DDDDDD(title="hello")</li> </ul> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { // 1. Select the element whose id is div 1 $('#div1').css('background', 'red') // 2. Select all div elements $('div').css('background', 'red') // 3. Select all elements whose class attribute is box $('.box').css('background', 'red') // 4. Select all div and span elements $('div,span').css('background', 'red') // 5. Select div elements with all class attributes box $('div.box').css('background', 'red') //Can't write. box div }) </script> </body> </html>
5.3 Hierarchical Selector
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>06_Hierarchical selector</title> </head> <body> <ul> <li>AAAAA</li> <li class="box">CCCCC</li> <li title="hello"><span>BBBBB</span></li> <li title="hello"><span>DDDD</span></li> <span>EEEEE</span> </ul> <!-- Hierarchical selector: Find child elements, Descendant elements, Brother Element Selector 1. ancestor descendant Matching all descendant elements under a given ancestor element 2. parent>child Matching all child elements under a given parent element 3. prev+next Match all immediately in prev Post-elemental next element 4. prev~siblings matching prev All after the element siblings element --> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //1. Select all span under ul $('ul span').css('background', 'red') //2. Select all child elements span under ul $('ul>span').css('background', 'red') //3. Select the next li with class box $('.box+li').css('background', 'red') //4. Select all sibling elements after the class box element under ul $('ul .box~*').css('background', 'red') }) </script> </body> </html>
5.4 filter selector
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>07_Filter selector</title> </head> <body> <div id="div1" class="box">class by box Of div1</div> <div id="div2" class="box">class by box Of div2</div> <div id="div3">div3</div> <span class="box">class by box Of span</span> <br/> <ul> <li>AAAAA</li> <li title="hello">BBBBB</li> <li class="box">CCCCC</li> <li title="hello">DDDDDD</li> <li title="two">BBBBB</li> <li style="display:none">I was hiding</li> </ul> <!-- A selector that filters further among the elements matched by the original selector * basic * content * visibility * attribute --> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //1. Select the first div $('div:first').css('background', 'red') //2. Select the last class as the box element $('.box:last').css('background', 'red') //3. Select div s that all class attributes are not box $('div:not(.box)').css('background', 'red') //4. Select the second and third li elements $('li:gt(0):lt(2)').css('background', 'red') //Index start position changes, restart calculation $('li:lt(3):gt(0)').css('background', 'red') //Correct Index Location //5. Choose li for BBBBB $('li:contains(BBBBB)').css('background', 'red') //6. Select hidden li $('li:hidden ').show() //7. Select the li element with title attribute $('li[title]').css('background', 'red') //8. Select all attribute title s as the li element of hello $('li[title=hello]').css('background', 'red') }) </script> </body> </html>
5.5 Form Selector
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>08_Form selector</title> </head> <body> <form> User name: <input type="text"/><br> Password: <input type="password"/><br> Hobbies: <input type="checkbox" checked="checked"/>Basketball <input type="checkbox" checked="checked"/>Football <input type="checkbox" checked="checked"/>Badminton <br> Gender: <input type="radio" name="sex" value='male'/>male <input type="radio" name="sex" value='female'/>female<br> Mailbox: <input type="text" name="email" disabled="disabled"/><br> Location: <select> <option value="1">Beijing</option> <option value="2" selected="selected">Tianjin</option> <option value="3">Hebei</option> </select><br> <input type="submit" value="Submission"/> </form> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //1. Select an unavailable text input box $(':input:disabled').css('background', 'red') //2. Display the number of preferences selected console.log($(':checkbox:checked').length) //3. Display the selected city name console.log($('select>option:selected').html()) console.log($('select').val()) //What you get is the value of the selected option }) </script> </body> </html>
6. $Tool Approach
//1. $.each(): traverse data in an array or object var person = { name: 'tom', age: 12 } $.each(person, function (key, value) { console.log(key, value) }) //2. $.trim(): Remove whitespace on both sides of the string //3. $.type(obj): Get the type of data console.log($.type($) === "function") // true //4. $.isArray(obj): Determine whether an array is an array console.log($.isArray($())) //false console.log($.isArray([])) //true //5. $.isFunction(obj): Determine whether it is a function console.log($.isFunction($)) //true console.log($.isFunction($())) //false //6. $.parseJSON(json): parsing JSON strings to convert js objects / arrays /* json There are two types as a whole: 1.json Object: {key1: value1, key2: value2} 2. json Array: [value1, value2] 3. key It can only be a string. 4. value Types: number string boolean null [] {} */ var json = '{"username":"jack", "age" : 12}' console.log($.parseJSON(json)) //js object json = '[{"username":"jack", "age" : 12},{"username":"Tom", "age" : 13}]' console.log($.parseJSON(json)) //js array /* JSON.parse(jsonString) // json String - --> JS object / array JSON.stringify(JSObject/JSArr) // js Object/Array - - > JSON String */
7. Attributes
- Manipulating tag attributes, tag body text
- attr(name) / attr(name, value): read and write label attributes for non-Boolean values
- prop(name) / prop(name, value): Tag properties for reading and writing Boolean values
- removeAttr(name)/removeProp(name): Delete attributes
- addClass(classValue): Add class
- removeClass(classValue): Remove the specified class
- val() / val(value): the value of the read and write tag
- HTML ()/ HTML (htmlString): Read and write tagged text
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>10_attribute</title> </head> <body> <div id="div1" class="box" title="one">class by box Of div1</div> <div id="div2" class="box" title="two">class by box Of div2</div> <div id="div3">div3</div> <span class="box">class by box Of span</span><br/> <ul> <li>AAAAA</li> <li title="hello" class="box2">BBBBB</li> <li class="box">CCCCC</li> <li title="hello">DDDDDD</li> <li title="two"><span>BBBBB</span></li> </ul> <input type="text" name="username" value="guiguClass"/><br> <input type="checkbox"> <input type="checkbox"><br> <button>Selection</button> <button>Trim White Space</button> <!-- 1. Operate on arbitrary attributes attr() removeAttr() prop() 2. operation class attribute addClass() removeClass() 3. operation HTML Code/text/value html() val() --> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { // 1. Read the title attribute of the first div console.log($('div:first').attr('title')) // 2. Set the name attribute for all div s (value is atguigu) $('div').attr('name', 'atguigu') // 3. Remove title attributes for all div s $('div').removeAttr('title') // 4. Set class='guiguClass'for all div s $('div').attr('class', 'guiguClass') // 5. Add class values (abc) to all div s $('div').addClass('abc') // 6. Remove the class of guiguClass for all div s $('div').removeClass('guiguClass') // 7. Get the label body text of the last li console.log($('li:last').html()) // 8. Set the label body of the first li to "<h1>mmmmmmmmm</h1>" $('li:first').html('<h1>mmmmmmmmm</h1>') // 9. Get the value in the input box console.log($(':text').val()) // 10. Set the value of the input box to atguigu $(':text').val('atguigu') // 11. Click on the'All Selection'button to achieve the All Selection $('button:first').click(function () { $(':checkbox').prop('checked', true) }) // 12. Click on the'No Selection'button to achieve the'No Selection'. $('button:last').click(function () { $(':checkbox').prop('checked', false) }) }) </script> </body> </html>
8. CSS
8.1 CSS
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>11_css</title> </head> <body> <p style="color: blue;">Descendants of Silicon Valley</p> <p style="color: green;">A descendant of the sun</p> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //1. Get the color of the first p tag console.log($('p:first').css('color')) //2. Set the text color of all p tags to red $('p').css('color', 'red') //3. Set the font color of the 2nd p (#ff0011), background (blue), width (300px), height (30px)// object $('p:eq(1)').css({ color: '#ff0011', background: 'blue', width: 300, height: 30 }) }) </script> </body> </html>
8.2 offset and position
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>12_offset and position</title> </head> <style type="text/css"> * { margin: 0px; } .div1 { position: absolute; width: 200px; height: 200px; top: 20px; left: 10px; background: blue; } .div2 { position: absolute; width: 100px; height: 100px; top: 50px; background: red; } .div3 { position: absolute; top: 250px; } </style> <body style="height: 2000px;"> <div class="div1"> <div class="div2">test offset</div> </div> <div class='div3'> <button id="btn1">read offset and position</button> <button id="btn2">Set up offset</button> </div> <!-- //Get/Set Label Location Data * offset(): Coordinates relative to the top left corner of the page * position(): Coordinates relative to the upper left corner of the parent element --> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> /* Demand: 1. Click btn1 Print the position of div1 relative to the top left corner of the page Print the position of div2 relative to the top left corner of the page Print the position of div1 relative to the upper left corner of the parent element Print the position of div2 relative to the upper left corner of the parent element 2. Click btn2 Set the position of div2 relative to the top left corner of the page */ $(function () { // Read offset and position $('#btn1').click(function () { var offset1 = $('.div1').offset() console.log(offset1.left, offset1.top) // 10 20 var offset2 = $('.div2').offset() console.log(offset2.left, offset2.top) // 10 70 var position1 = $('.div1').position() console.log(position1.left, position1.top) // 10 20 var position2 = $('.div2').position() console.log(position2.left, position2.top) // 0 50 }) // Setting offset $('#btn2').click(function () { $('.div2').offset({ left: 20, top: 40 }) }) }) </script> </body> </html>
8.3 ScollTop, scrollLeft and Back to the Top Case
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>13_Element scroll</title> </head> <body style="height: 2000px;"> <div style="border:1px solid black;width:100px;height:150px;overflow:auto"> This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. his is some text. </div><br><br><br> <button id="btn1">obtain scrollTop</button> <button id="btn2">Set up scrollTop</button> <!-- 1. scrollTop(): //Read/set the Y coordinates of the scrollbar 2. $(document.body).scrollTop()+$(document.documentElement).scrollTop() //Read the Y coordinates of the page scrollbar (compatible with chrome and IE) 3. $('body,html').scrollTop(60); //Scroll to the specified location (compatible with chrome and IE) --> <script src="js/jquery-1.10.1.js"></script> <script> $(function () { // 1. Get the coordinates of the div or page scrollbar $('#btn1').click(function () { console.log($('div').scrollTop()) console.log($('body').scrollTop() + $('html').scrollTop()) console.log($(document.body).scrollTop() + $(document.documentElement).scrollTop()) }) // 2. Scroll a div or page scrollbar to a specified location $('#btn2').click(function () { $('div').scrollTop(150) $('body, html').scrollTop(200) }) }) </script> </body> </html>
- Back to the top case
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>03_Back to the top</title> <style> #to_top { width: 30px; height: 40px; font: 14px/20px arial; text-align: center; background: #06c; position: fixed; cursor: pointer; color: #fff; left: 1250px; top: 500px; } </style> </head> <body style="height: 2000px;"> <div id="to_top">Return to the top</div> <script src="jquery-1.10.1.js"></script> <script> $(function () { //Back to the top $('#to_top').click(function () { var $body = $(document.body) var $html = $(document.documentElement) //Using scrollTop(): Scroll to the top instantaneously // $('html,body').scrollTop(0) //Using scrollTop(): Smoothly scroll to the top var offset = $body.scrollTop() + $html.scrollTop() if(offset===0) { return } var totalTime = 300 // Total time var intervalTime = 30 // Interval time var itemOffset = offset/(totalTime/intervalTime) var intervalId = setInterval(function () { // Continuous rolling with a circular timer offset -= itemOffset if(offset<=0) { offset = 0 clearInterval(intervalId) // Arrive at the top, stop the timer } $('html,body').scrollTop(offset) }, intervalTime) //Using animation: Smooth scroll to the top // $('body,html').animate({scrollTop:0},300) }) }); </script> </body> </html>
Dimensions of 8.4 Elements
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>14_Dimensions of elements</title> </head> <style> div { width: 100px; height: 150px; background: red; padding: 10px; border: 10px #fbd850 solid; margin: 10px; } </style> </head> <body> <div>div</div> <!-- 1. Content Size height(): height width(): width 2. Internal dimensions innerHeight(): height+padding innerWidth(): width+padding 3. External dimensions outerHeight(false/true): height+padding+border If it is true, Add margin outerWidth(false/true): width+padding+border If it is true, Add margin --> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script> $(function () { var $div = $('div') // Content Size console.log($div.width(), $div.height()) // 100 150 // Internal dimensions console.log($div.innerWidth(), $div.innerHeight()) // 120 170 //External dimensions console.log($div.outerWidth(), $div.outerHeight()) // 140 190 console.log($div.outerWidth(true), $div.outerHeight(true)) // 160 210 }) </script> </body> </html>
9. Screening
9.1 Filtration
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>15_screen_filter</title> </head> <body> <ul> <li>AAAAA</li> <li title="hello" class="box2">BBBBB</li> <li class="box">CCCCC</li> <li title="hello">DDDDDD</li> <li title="two"><span>BBBBB</span></li> </ul> <li>eeeee</li> <li>EEEEE</li><br> <!-- //Filter out some elements from the array of element objects in jQuery objects 1. first() 2. last() 3. eq(index|-index) 4. filter(selector) 5. not(selector) 6. has(selector) --> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { var $lis = $('ul>li'); //1. The first li label under UL $lis.first().css('background', 'red') //2. The last li tag under UL $lis.last().css('background', 'red') //3. The second of the li tag under UL $lis.eq(1).css('background', 'red') //4. The title attribute in the li tag under UL is hello $lis.filter('[title=hello]').css('background', 'red') //5. The title attribute in the li tag under UL is not hello $lis.not('[title=hello]').css('background', 'red') $lis.filter('[title][title!=hello]').css('background', 'red')// Have title attribute and attribute is not hello //6. Under ul, there are span subtags in the li tag $lis.has('span').css('background', 'red') }) </script> </body> </html>
9.2 Search - Find child elements, sibling elements, parent elements
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>16_screen_Search for children-parent-Brother label</title> </head> <body> <div id="div1" class="box" title="one">class by box Of div1</div> <div id="div2" class="box">class by box Of div2</div> <div id="div3">div3</div> <span class="box">class by box Of span</span> <br/> <div> <ul> <span>span Text 1</span> <li>AAAAA</li> <li title="hello" class="box2">BBBBB</li> <li class="box" id='cc'>CCCCC</li> <li title="hello">DDDDDD</li> <li title="two"><span>span Text 2</span></li> <span>span Text 3</span> </ul> <span>span Text 444</span><br> <li>eeeee</li> <li>EEEEE</li> <br> </div> <!-- Search for children by selector in the set of matched elements/parent/Brother label 1. children(): Find in subtags 2. find() : Search in descendant label 3. parent() : Parent label 4. prevAll() : All the brothers'labels in front 5. nextAll() : All the brothers'labels at the back 6. siblings() : All brothers'labels before and after --> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { var $ul = $('ul') // 1. The second span subtag of UL tag // $ul.children('span:eq(1)').css('background', 'red') // 2. The second span descendant label of UL label // $ul.find('span:eq(1)').css('background', 'red') // 3. The parent tag of UL tag // $ul.parent().css('background', 'red') // 4. All li tags in front of the li tag whose ID is cc // $ul.children('#cc').prevAll('li').css('background', 'red') // 5. All sibling li tags with ID cc's li tag // $ul.children('#cc').siblings('li').css('background', 'red') }) </script> </body> </html>
10. Hobby selector
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Selected exercises</title> </head> <body> <form> //What's your favorite sport? <input type="checkbox" id="checked AllBox"/> all/none <br/> <input type="checkbox" name="items" value="Football"/>Football <input type="checkbox" name="items" value="Basketball"/>Basketball <input type="checkbox" name="items" value="Badminton"/>Badminton <input type="checkbox" name="items" value="Table Tennis"/>Table Tennis <br/> <input type="button" id="checkedAllBtn" value="whole choose"/> <input type="button" id="checkedNoBtn" value="Not at all"/> <input type="button" id="checkedRevBtn" value="back choose"/> <input type="button" id="sendBtn" value="carry hand over"/> </form> <script src="jquery-1.10.1.js"></script> <script type="text/javascript"> $(function () { var $Items = $(':checkbox[name=items]') var $checkedAllBox = $('#checkedAllBox') // 1. Click'All Choices': Choose All Hobbies $('#checkedAllBtn').click(function () { $Items.prop('checked', true) $checkedAllBox.prop('checked', true) }) // 2. Click'No Choice': All Hobbies Are Not Checked $('#checkedNoBtn').click(function () { $Items.prop('checked', false) $checkedAllBox.prop('checked', false) }) // 3. Click'Revoke': Change the checking status of all hobbies $('#checkedRevBtn').click(function () { $Items.each(function () { this.checked = !this.checked }) $checkedAllBox.prop('checked', $Items.filter(':not(:checked)').size()===0) }) // 4. Click'All Choices / No Choices': Choose All Hobbies, or No Choices $checkedAllBox.click(function () { $Items.prop('checked', this.checked) }) // 5. When you click on a hobby, update the selection status of'all/none'when necessary. $Items.click(function () { $checkedAllBox.prop('checked', $Items.filter(':not(:checked)').size()===0) }) // 6. Click'Submit': Tips for all hobbies checked $('#sendBtn').click(function () { $Items.filter(':checked').each(function () { alert(this.value) }) }) }) </script> </body> </html>
11. Document Processing - Add, Delete and Change
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>17_File_Addition, deletion and modification</title> </head> <style type="text/css"> * { margin: 0px; } .div1 { position: absolute; width: 200px; height: 200px; top: 20px; left: 10px; background: blue; } .div2 { position: absolute; width: 100px; height: 100px; /*top: 50px;*/ background: red; } .div3 { position: absolute; top: 250px; } </style> <body> <ul id="ul1"> <li>AAAAA</li> <li title="hello">BBBBB</li> <li class="box">CCCCC</li> <li title="hello">DDDDDD</li> <li title="two">EEEEE</li> <li>FFFFF</li> </ul><br><br> <ul id="ul2"> <li>aaa</li> <li title="hello">bbb</li> <li class="box">ccc</li> <li title="hello">ddd</li> <li title="two">eee</li> </ul> <!-- 1. Add to/Replacement element * append(content) Insert the specified content into the last of all currently matched elements * prepend(content) Insert the specified content to the front of all currently matched elements * before(content) Insert the specified content before all current matching elements * after(content) Insert the specified content behind all current matching elements to replace the node * replaceWith(content) Replace all matching tags with specified contents to delete nodes 2. Delete elements * empty() Delete child elements of all matching elements * remove() Delete all matching elements --> <script src="js/jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //1. Add a span to ul with id ul 1 (last) $('#Ul1'). append ('< span > append () added span </span >') $('<span>appendTo()Additional span</span>').appendTo('#ul1') //2. Add a span (front) to ul with id ul1 $('#Ul1'). prepend ('< span > prepend () added span </span >') $('<span>prependTo()Additional span</span>').prependTo('#ul1') //3. Add span before li(title is hello) under ul with id ul1 $('#UL1 > Li [title = hello]'. before ('< span > before () add span </span >') //4. Add span after li(title is hello) under ul with id ul1 $('#UL1 > Li [title = hello]'. after ('< span > after () add span < / span >') //5. Replace all li(title is hello) under ul with id ul2 with p $('#UL1 > Li [title = hello]'. replaceWith ('< P > replaceWith () replaced by P </p >') //6. Remove all li under ul with id ul2 $('#ul2').empty() }); </script> </body> </html>
12. Cases of adding or deleting records
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Add delete record exercise</title> <link rel="stylesheet" type="text/css" href="css.css"/> </head> <body> <table id="employeeTable"> <tr> <th>Name</th> <th>Email</th> <th>Salary</th> <th> </th> </tr> <tr> <td>Tom</td> <td>tom@tom.com</td> <td>5000</td> <td><a href="deleteEmp?id=001">Delete</a></td> </tr> <tr> <td>Jerry</td> <td>jerry@sohu.com</td> <td>8000</td> <td><a href="deleteEmp?id=002">Delete</a></td> </tr> <tr> <td>Bob</td> <td>bob@tom.com</td> <td>10000</td> <td><a href="deleteEmp?id=003">Delete</a></td> </tr> </table> <div id="formDiv"> <h4>Adding new employees</h4> <table> <tr> <td class="word">name:</td> <td class="inp"> <input type="text" name="empName" id="empName"/> </td> </tr> <tr> <td class="word">email:</td> <td class="inp"> <input type="text" name="email" id="email"/> </td> </tr> <tr> <td class="word">salary:</td> <td class="inp"> <input type="text" name="salary" id="salary"/> </td> </tr> <tr> <td colspan="2" align="center"> <button id="addEmpButton" value="abc"> Submit </button> </td> </tr> </table> </div> <script src="jquery-1.10.1.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> /* Functional description: 1. Click on'Submit'to generate a line of employee information in the form based on the input information 2. Click on the Delete link, prompt to delete the current line information, and click OK to delete the information. Technical points: 1. DOM query 2. Binding event monitoring 3. DOM Addition, deletion and modification 4. Cancel the default behavior of events */ $(function () { $('#addEmpButton').click(function () { var $empName = $('#empName') var $email = $('#email') var $salary = $('#salary') var empName = $empName.val() var email = $empName.val() var salary = $empName.val() var id = Date.now() $('<tr></tr>') .append('<td>'+empName+'</td>') .append('<td>'+email+'</td>') .append('<td>'+salary+'</td>') .append('<td><a href="deleteEmp?id="'+id+'>Delete</a></td>') .appendTo('#employeeTable') .find('a') .click(clickA) $empName.val('') $email.val('') $salary.val('') }) $('a').click(clickA) function clickA (event) { event.preventDefault() var $tr = $(this).parent().parent() var name = $tr.children('td:first').html() if(confirm('Determine deletion'+name+'Do you?')) { $tr.remove() } } }) </script> </body> </html>