$JQuery learning notes

$JQuery learning notes

1, Meet jquery

1. The top-level object in jQuery is $or jQuery

be used for

  • Get jquery object

  • Entry function (page load event)

  • Advanced features

    Note: the $and jQuery keywords in jQuery are the same object

    $can be considered as a constructor

    • You can call $(selector) to get an object, and then you can call the instance method of $

    • You can also use $ Method name calls a static method. For example, traverse the $. Of an array object each() is equivalent to a for loop

2. Page loading events in jQuery (good habits should be written)

Three steps to use jquery:

  • Import jquery file

  • Entry function (defining page loading events)

  • Function realization

    About the entry function of jquery:

    //The first way is to prepare the whole document and then execute the content in the function
    $(document).ready(function(){
    
    });
    
    //The second way to write it is a simplified version
    $().ready(function(){
    
    })
    
    //The third way of writing is also a simplified version, which is the simplest form
    $(function(){
    
    })
    

    jquery entry function and window Onload comparison

    • The JavaScript entry function cannot be executed until all resources (including images and files) on the page are loaded
    • The entry function of jquery will only wait for the document tree to be loaded and fully executed, and will not wait for the images and files to be loaded.

2, Selector

1. Basic selectors for jquery

  • The ID selector $('#id') gets the element with the specified ID

  • Class selector $('. Class') gets the elements of the same class

  • Tag selector $('div ') gets all elements of the same type of tag

  • The union selector $('div,p,li') is separated by commas, as long as one of the conditions is met

  • The intersection selector $('div.redclass') gets the div element whose class is redclass

  • Arbitrary selector $('*')

    Conclusion: as like as two peas of css,

2. jquery hierarchy selector

The descendant selector $('UL > Li') uses the greater than sign > to obtain the elements of the child level. Note that the elements of the child level will not be obtained

The descendant selector $('ul li') uses spaces to represent the descendant selector and obtain all li elements under ul, including grandchildren, etc

Other level selectors:

prev+next means to find the previous element plus the next element

prev ~sibbling means to find the sibling element of the previous element

Conclusion: as like as two peas of css,

3. jquery filter selector

  • All selectors of this type should have a colon:

    nameusagedescribe
    :eq$('li:eq(2)').css('color','red')Get the li element and select the element with index number 2. The index number starts from 0
    :odd$('li:odd').css('color','red')Get the li element and select the element with odd index number
    :even$('li:even').css('color','red')Get the li element and select the element with an even index number

    Other filter selectors with colons:

    : frist $('li:frist') find the first one

    : last $('li:last ') find the last one

    : not(selector) $('div:not(img)') find div without img tag

    : gt(index) $('li:gt(2) ') find a Li tag with a subscript greater than 2

    : lt(index) $('li:lt(2) ') find a Li tag with a subscript less than 2

    : header $('div:header') find tags such as H1, H2 and H3 in div tags

    : animated animated labels

    : fous focus tab

4. jquery filtering method

  • The function of filter selector is similar to that of filter, but the usage is different. Filter selector is mainly method

    nameusagedescribe
    children(selector)$('ul').childern('li')Equivalent to $('ul > Li '), subclass selector
    find(selector)$('ul').find('li')Equivalent to $('ul li '), descendant selector
    sibling(selector)$('#first').sibling('li')Find sibling nodes, excluding itself
    parent()$('li').parent()Find parent node
    eq(index)$('li').eq(2)Find li element with subscript 2
    next()$('li').next()Find next brother
    prev()$('li').prev()Find previous brother
    closest$('li').closet('div')Find his nearest div ancestor element

5. Find tags based on content in jquery

: contains(text) find the label according to the text content

empty: find a tag that has nothing

: the parent cannot find the element tag that is the father

: has(selector) find the element label with the label corresponding to the selector

6. Find labels based on visibility in jquery

: Hidden hidden label

: visible visible label

7. Find tags based on attributes in jquery

Attribute ==== > attribute

[attribute] find by attribute

[attribute=value] search by attribute and attribute value

[attribute!=value]

[attribute^=value] attribute value starts with this

[attribute$=value] attribute value ends with this

[attribute*=value] arbitrary

The [attribute1] [attribute2] [attribute3] [attribute4] table is a union of multiple attributes

8. jquery find child elements

:nth-child

:frist-child

:last-child

:only-child

9. Find form elements in jquery

:input

:text

:password

:radio

...

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="w">
			<input  name="in" id="q" value="" class="qq"/>
			<input  name="i"  value="" class="qq" name="oo"/>
			<input  name="n" id="p" value=""  />
		</div>
		
	</body>
	<script src="./jquery.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
		console.log($('input'))
		console.log($('input')[0])
		console.log($('.qq'))
		console.log($('input[name=oo]'))
		console.log($('input#in'))
		console.log($('.qq').parent())
	</script>
</html>

3, Relationship between jquery object and dom object

1. Related code demonstration

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>jquery Object and DOM object</title>
	</head>
	<script src="./jquery.js" type="text/javascript" charset="utf-8"></script>
	<body>
		<input type="button"  id="btn" value="Point me" />
	</body>
	<script type="text/javascript">
		console.log($('#btn'));// The returned is a jq object
		console.log($('#btn')[0]);// The JQ object contains the dom object
		console.log(document.getElementById('btn'))
		//==============================
		 var box =document.getElementById('box');
		box.innerHTML = 'hello'; // Method of dom object
		var $box = $('#box');
		
		//--------------------------------
		
		$box.text('hello')   //Method of jq object
		$box.html('nhao')	
		
		//===============================
		//Difference: the jq object calls the attribute method of the jq object
		// dom objects call the properties and methods that dom wants
		
	</script>
</html>

2. Conversion between jq object and dom object

  • Converting dom objects to jq objects
    • One way is $(dom object)
  • Convert jq object to dom object
    • There are two ways
      • Remove subscript $('div') [0]
      • Call the get method to pass the subscript $('div') get(0)

4, Simple event binding

1. Binding of simple events in jquery $('#btn') click(function(){})

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>
			Simple event binding
		</title>
	</head>
	<body>
		<input type="button" name="" id="btn" value="Order me" />
		<input type="text" name=" " id=" text" />
	</body>
	
	<script src="./jquery.js" type="text/javascript" charset="utf-8"></script>
	
	<script type="text/javascript">
				//Bind event to input - Native Writing
				document.getElementById('btn').onclick = function(){
					// alert('Hello ');
				}
				
				//The introduction of jquery does not require writing on, and directly calls the click function to pass a function as a parameter 
				$('#btn').click(function(){
					alert('Hello');
				})
				//Lose focus
				$('#text').blur(function(){
					console.log("I lost focus^~^");
				})
				//Get focus
				$('#text').focus(function(){
					console.log("I lost focus^~^");
				})
				
				//*****Bind mouseover function to all input tags without looping
				$('input').mouseover(function(){
					console.log("How do you do");
				})
	</script>
</html>

Note: the writing method of jquery does not need to write on. Directly call the click function to pass a function as a parameter

5, jQuery operation properties

1. val() / text() / html() and this

$obj.val()    //Gets or sets the value attribute value of the table cell element

$obj.html()   //The corresponding innerHTML in the dom object = = > this will compile the HTML code inside

$obj.text()   //The innerText = = > in the corresponding dom object will output the obtained data as a string

*******Note that the above three do not pass parameters, which means to obtain values;
*******Pass the parameter to represent the value set to the label



console.log($('#text').blur(function(){
					console.log($(this).val())   //This indicates that the current tag #text this is a dom object
				}))
				
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>
			Simple event binding
		</title>
	</head>
	<body>
		<input type="text" id="btn">
		<span id="span"></span>
			<input type="button" name="" id="add" value="+" />
		<input type="text" name="" id="text" value="0" />
		<input type="button" name="" id="sub" value="-" />
	</body>
	
	<script src="./jquery.js" type="text/javascript" charset="utf-8"></script>
	
	<script type="text/javascript">
				$(function(){
					$('#btn').blur(function(){
						var phonenum = $(this).val();
						console.log(phonenum);
						if(phonenum == /^1[3-9]\d{9}$/ ){    //regular expression 
							$('#span').text('correct ') css('color','green');
						}else if(phonenum == ''){
							$('#span').text('number cannot be empty ') css('color','red')
						}
						else{
							$('#span').text('incorrect number format ') css('color','red')
						}
					})
					
					
					
					$('#add').click(function(){
						//Gets the value in the input box
						var number = parseInt($('#text').val())+1;
						$('#text').val(number);
					})
				
				
				$('#sub').click(function(){
						//Gets the value in the input box
						var number = parseInt($('#text').val())-1;
						if(number<=0){
							number=0;
						}
						$('#text').val(number);
				});
				
	</script>
</html>

Pay attention to learning regular expressions

Supplement: number of reserved digits to display the decimal part ToFixed (2) = = > two decimal places (in Google browser, there is a bug for very few numbers)

2. Select all button of CheckBox

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>
			Simple event binding
		</title>
	</head>
	<body>
		<div>
			<input type="checkbox"  id="cbox1" />Basketball
			<input type="checkbox"  id="cbox2"  />Tennis
			<input type="checkbox"  id="cbox3"  />Volleyball
			<input type="checkbox"  id="cbox4"  />Football
		</div>
		<input type="checkbox" id="all" />Select all
	</body>
	
	<script src="./jquery.js" type="text/javascript" charset="utf-8"></script>
	
	<script type="text/javascript">
		
		//Select all affects all checkbox es
			$('#all').change(function(){
				//Get the properties of all selected checkboxes
				// console.log(this.checked)
				// var status = this.checked;
				var status = $(this).prop('checked')//The prop method passes an attribute name, which means to obtain a value, and passes a name and a value, which means to set
				$('#cbox1').parent().find('input').prop('checked',status)	;
				
			})
			//Each row affects the selection of all
				$('#cbox1').parent().children('input').change(function(){
					//Judge whether the number of all rows is equal to the number of selected rows
					
					var totall = $('#cbox1').parent().children('input').length;
					//Number of selected rows
					var checkednum = $('#cbox1').parent().children('input:checked').length
					var status = checkednum == total;
					$('#all').prop('checked',status)
					
				})
		
	</script>
</html>

Note: the prop method passes an attribute name, which means to obtain a value, and passes a name and a value, which means to set

3. attr add and set attribute operations

  • Set individual properties

    //First parameter: attribute name needs to be set
    //Second parameter: corresponding attribute value
    //$obj.attr(name,value)
    
    $('img').attr('title','Oh, good')
    $('div').atrr('class','hhh');
    
  • Set multiple properties

    //A parameter is an object that contains the property name and value to be set
    //$obj.attr(obj)
    
    $('div').attr({
    	class:'hhh',
    	id:'eee',
    	style:'color:red'//  ****Note that this is to change its original value to the value of the current string, so keep the previous attribute, and then assign a value to / / style in the form of character splicing
    })
    

4. removeAttr remove attribute

$('div').removeAttr('data')  

5. prop operation (attribute value is boolean)

  • In jquery1 Support after 6. For Boolean attributes such as checked, selected and disabled, the attr method cannot be used, but the prop method can only be used
//set a property
$(':checked').prop('checked',true)

//get attribute

$(':checked').prop('checked')

6. class operation addClass (add) removeclass (remove) hasclass (exist) toggleclass (replace)

  • Add style $obj addClass(name)
//Name: the name of the style class to be added. Note that the parameters should not be dotted
//$obj.addClass(name);
//Column, add one style to all input s
$('input').addClass('one');

  • Remove style $obj removeClass(name);
//Name: the name of the removed style class. Note that the parameter should not be dotted
//$obj.addClass(name);
//Column, remove the style of one for all input s
$('input').removeClass('one');

  • Determine whether there is this style $obj Hasclass ('one ') = = = > get a Boolean value

    //Name: judge the style class name of the. Note that the parameter should not be dotted. If there is, it will return a true value
    //$obj.hasClass(name);
    //Column, remove the style of one for all input s
    $('input').hasClass('one');
    
  • Switch style $obj toggleClass(‘one’)

    //Name: the name of the style class to be switched. Note that the parameter should not be dotted. If there is, delete the style. If not, add the style
    //$obj.toggleClass(name);
    //Column, remove the style of one for all input s
    $('input').toggleClass('one');
    

7. Implicit iteration (automatic traversal of batch operation)

  • 1. When setting the operation (event binding), if there are multiple elements, all elements set the same value
  • 2. If there are multiple elements, only the value of the first element will be returned

6, jQuery operation style

1. css operation

  • Function: set or modify the style. The operation is the style attribute

  • Operate on a single style

    //Name: required style name
    //Value: the corresponding style value
    ///$obj.css(name,value);
    //Use case list
    $('#one').css('background','red ') / / change the background color to red
    
    //Native is to use labels style ='font-size:30px;width:200px'
    
  • Set multiple styles

    Note: key can be enclosed in quotation marks or not, but value must be enclosed in quotation marks

    //A parameter is an object that contains the style and style value to be set
    //$obj.css(obj)
    //Use case
    $('#one'). CSS ({/ / key can be caused by quotation marks or not, but value must be caused by quotation marks
    	'backgrond':'gray',
    	height:'400px',
    	'width':'200px'
    	
    })
    
  • Get style

    //Name: required style name
    
    ///$obj.css(name);
    //Use case list
    $('#one').css('background ') / / get the style of the background
    //Note that the get style operation will only return the style value of one element
    

    Note: the get style operation will only return the style value of one element

2. jQuery size and position operations

2.1 width method and height method

Set or get the height, excluding the inner margin, border and outer margin

//With parameters indicates the set height
$('img').height(200);
//Parameter acquisition height not found
$('img').height()

Gets the width and height of the visible area of the web page

//Gets the width of the viewing area
$(window).width();
//Gets the height of the viewing area
$(window).heigth();
2.2,innerWidth / innerHeight / outerWidth / outerHeigth()
innerWidth() /innerHeight()    Method returns the width and height of the element(Include inner margin)
outerWidth() / outerHeight()    Method returns the width and height of the element, including the inner margin and border)
outerWidth(true) / outerHeight(true)	Method returns the width and height of the element (including inner margin, border and outer margin)
2.3. srcollTop and srcolleft

Set or get the position of the scroll bar

//Gets the height at which the page is curled
$(window).srcollTop();
//Gets the width of the curled page
$(window).srcollLeft();
2.4. offset method and position method

The offset method obtains the position of the element from the document, and the position method obtains the position of the element from the positioned parent element (offsetParent)

//Get the position of the element from the document, and the return value is the object: {left:100,top:100}
$(selector).offset();
//Gets the position of the nearest positional parent element relative to the
$(selector).position();

7, each method traversal

1. The implicit iteration of jQuery will set the same value for all Dom objects, but if we need to set different values for each object, we need to iterate by ourselves

Function: traverse the collection of objects in jQuery and execute a function for each matching element

//Parameter one represents the index number in all matching elements of the current element
//Parameter 2 represents the current element (DOM object)
$(selector).each(function(index,element){ //Is the method of dynamic table

})



$.each($('div'),function(index,v){})   //Is a static method

2. Total price calculation case in shopping cart:

The total price is calculated and encapsulated into a function

		1.First, analyze the steps
		2.Fill in the code according to the steps
		
		function change_total() {
			//Select the row in the
			//Traversal, according to each selected checkedbox, get the current
			var total_price = 0;
			var total_num = 0;
			$('.row_checked:checked').each(function(index,v){
			//Gets the number of items in the current line
				var num = parseInt($(v).closet('ul').find('.current_number').val());
				//Get the unit price in the current line of the document
				var price = parseFloat($(v).closet('ul').find('.sum').html()).toFixed(2);
				//Cumulative subtotal
				total_price += num*price;
				total_num += num;
			})

8, JQuery event binding mechanism

  • Event binding has been learned in JavaScript. jQuery encapsulates JavaScript event binding and adds and extends the time processing mechanism. jQuery not only provides more elegant event processing syntax, but also greatly enhances the ability of event processing.

1. Development of jQuery events

  • Simple event binding - bind event - delegate event - on event binding
1.1. Simple event binding
click(hander)   //Click event
mouseenter(hander)   //Mouse entry event
mouseave(hander)     //Mouse leaving event
1.2. Register events in bind mode (not used)
//First parameter: type of event
//Second parameter: event handler
$('p').bind('click',function(){}) //You can bind multiple events at once, separated by spaces
1.3. delegate method binding event (not used)
//The first parameter: selector, the element to bind the event
//Second parameter: type of event
//Third parameter: event handler
$('.parentbox').delegate('p','click',function(){
	//be careful. Parentbox is the parent element before the p tag, expressed as All p tag binding events under parentbox
})
1.4. on method binding event (key)
  • on register simple events

    //Indicates that the event is bound to $(selector) and triggered by itself. Dynamic binding is not supported
    $(selector).on('click',functon(){})   
    
  • on register event delegation

    //Represents a proxy event bound to $(selector). This leave can only be triggered when it is an internal original element. Dynamic binding is supported
    $(selector).on('click','span',function(a){}); //The a parameter here is the trigger event object, and the current dom object can be obtained through a.target
    												//The event delegate can implement the same event binding for the added elements
    
  • Syntax of on registration event binding:

    //The first parameter: events. The name of the bound event can be multiple events separated by spaces (standard events or custom events)
    //The second parameter: selector, the descendant element of the execution event (optional). If there is no descendant element, the event will be executed by itself
    //The third parameter: data, the data passed to the processing function. When the event is triggered, it is passed through event Data to use (not often used)
    //The fourth parameter: handler, the function of event handling
    $(selector).on(events[,selector][,data],handler);
    

1.5 clone label (copy label)
var input1 = $('.input')[0].cloneNode();
1.6. Add sub label
$("#btn")[0].appendChild(selector)

2. Event unbinding

2.1. unbind mode (not used)
$(selector).unbind();//Unbind all
$(selector).unbind('click');//Unbind the specified
2.2 undelegate mode (not used)
$(selector).undelegate();//Dismiss all delegate events
$(selector).undelegate('click');//Unbind the specified
2.3 off method (key points)
//Unbind all events of matching elements
$(selector).off();
//Unbind all click events of matching elements
$(selector).off('click');

3. Trigger event

$(selector).click();  
$(selector).trigger('click')

4. jQuery event object

jQuery event object is actually an encapsulation of js event object, which handles compatibility.

//The screen corresponding to screenX and screenY is the value in the upper left corner
//The position of clientX and clientY from the upper left corner of the page (ignoring the scroll bar)
//The position of pageX and pagey from the upper left corner of the page (to calculate the scroll bar)


//event. Keycodekeyboard code pressed
//event.data stores the additional data passed from the binding

//event.stopPropagation() prevents event bubbling
//event.preventDefault() prevents the default behavior of the browser = = > page Jump and so on
//return false; Prevent event bubbling and the default behavior of the browser

9, Animation effect

1. show() shows, hide() hides, toggle() transforms

The first parameter: time indicates time. The default values are 0, slow(200),normal(400),fast(600)

The second parameter: function indicates the callback function after execution

$obj.show(time, function() {}) displays the object gradually in time

$obj.hide(time) gradually hides the object in time

$obj.toggle(time) converts an object between displaying and hiding in time

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Basic animation effects</title>
	</head>
	<body>
		<div id="div1">
			<input type="button" name="" id="show" value="click" />
			<input type="button" name="" id="hide" value="hide" />
			<input type="button" name="" id="toggle" value="switch" />
		</div>
		
		<div id="div2">
			<img src="../img/OIP%20(1).jpg" >
			<img src="../img/OIP%20(2).jpg" >
			<img src="../img/OIP.jpg" >
		</div>
	</body>
	<script src="./jquery.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
		$(function(){
			$('#show').click(function(){
				$('img').show(2000);
			})
			$('#hide').click(function(){
				$('img').hide(2000);
			})
			$('#toggle').click(function(){
				$('img').toggle(2000);
			})
		})
	</script>
</html>

2. slideUp() slides in, slideDown() fades out, and slideToggle() switches

The first parameter is time, and the default is normal slow fast

The second parameter is the function callback function

The change is the height of the picture. In order to see the effect, you need to set the height and width of the picture or component

  <!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Basic animation effects</title>
		<style type="text/css">
			img{
				width: 350px;
				height: 400px;
			}
		</style>
	</head>
	<body>
		<div id="div1">
			<input type="button" name="" id="show" value="click" />
			<input type="button" name="" id="hide" value="hide" />
			<input type="button" name="" id="toggle" value="switch" />
		</div>
		
		<div id="div2">
			<img src="../img/OIP%20(1).jpg" >
			<img src="../img/OIP%20(2).jpg" >
			<img src="../img/OIP.jpg" >
		</div>
	</body>
	<script src="./jquery.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
		$(function(){
			$('#show').click(function(){
				$('img').slideUp(2000);
			})
			$('#hide').click(function(){
				$('img').slideDown(2000);
			})
			$('#toggle').click(function(){
				$('img').slideToggle(2000);
			})
		})
	</script>
</html>

3. fadeIn() fadeOut() fadeToggle() switch

fadeTo(time,opacity) //opacity means transparency 1 ~ 0,

4. Custom animation

4.1. animate: custom animation
$(selector).animate({params},[speed],[easing],[callback]);
//{params}: css attribute to execute animation, with number (required)
//speed: duration of animation execution
//easing: execution effect. The default is swing, which can be linear
//Callback: callback function to be executed immediately after the animation is executed (optional)
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Basic animation effects</title>
		<style type="text/css">
			img{
				width: 350px;
				height: 400px;
			}
		</style>
	</head>
	<body>
		<div id="div1">
			<input type="button" name="" id="animate" value="custom" />
			
		</div>
		
		<div id="div2">
			<img src="../img/OIP%20(1).jpg" >
			
		</div>
		
		<input type="button" name="" id="" value="dddd" />
	</body>
	<script src="./jquery.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
		$(function(){
			$('#animate').click(function(){
				$('img').animate(
				{width:'100px',
				height:'100px',
				opacity:'0.5'
				},2000,'linear',function(){
					alert('succeed')
				})
			})
			
		
		})
	</script>
</html>

5. Stop Animation ()

$('img').stop()

stop(clearQueue,jumpToEnd)

//The first parameter: is the queue clear

//The second parameter: whether to jump or not is the final effect

6. Extend animation (delay)

$('img').delay()

$('img').hide(200).delay(200).show(200)
6.2 pull down of secondary menu
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title></title>
		<style type="text/css">
			
			div{
				width: 200px;
				height: 20px;
				background-color: gray;
			}
			ul{
				padding: 0;
				margin: 0;
				width: 200px;
			}
			li{
				list-style: none;
				background-color: yellow;
			}
			</style>
	</head>
	<body>
		<div id="div1" class="div">
			Top level menu 1
		</div>
		<ul>
			<li>11</li>
			<li>12</li>
			<li>13</li>
		</ul>
		<div id="div2" class="div">
			Top level menu 2
		</div>
		<ul>
			<li>21</li>
			<li>22</li>
			<li>23</li>
		</ul>
	</body>
	<script src="./jquery.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
		$('.div').click(function(){ //Bind click events to each top-level menu
			
			var that = this; 
            
			//var index='';
			//$('.div').each(function(i,v) {/ / obtain and click the subscript of the current top-level menu
			//	if(that == v)
			//	{
			//		index = i;
			//	}
			//})
			//$($('ul')[index]).slideToggle(1000) / / pull down and disappear the menu through replacement
			console.log(index)
			$(this).next().slideToggle(1000)  //The drop-down and disappearance of the menu are realized through replacement
		})
	</script>
</html>

10, jQuery node operation

1. Create node

document.createElement()

//$(htmlstr)
//Htmlstr: node in HTML format
$('<p>Hello</p>');

2. Add node

append	appendTo	Insert content at the end of the selected original	father.append(son)		son.appendTo(father)
prepend	prependTo	Insert content at the beginning of the selected element		father.prepend(son)	son.prependTo(father)
before	insertBefore	Insert content after the selected element		after.before(front)	front.insertBefore(after)
after	insertAfter	Insert content before the selected element		front.after(after)	after.insertAfter(front)
These are two ways of writing. It is recommended to remember the one in front

3. Clearing and deleting nodes

  • empty: clear all elements of the specified node and keep them (recommended, which will clear the events bound on the child elements)
$('div').empty();
  • remove: compared with empty, it can be deleted by itself
$('div').remove();

4. Clone node

  • Role: copy matching elements
//Assign $(selector) all matched elements (deep copy)
//CloneNode (true) / / the original JS cloneNode does not pass parameters. Clone the tag itself and pass the parameter true
/
pt">
		$('.div').click(function(){ //Bind click events to each top-level menu
			
			var that = this; 
            
			//var index='';
			//$('.div').each(function(i,v) {/ / obtain and click the subscript of the current top-level menu
			//	if(that == v)
			//	{
			//		index = i;
			//	}
			//})
			//$($('ul')[index]).slideToggle(1000) / / pull down and disappear the menu through replacement
			console.log(index)
			$(this).next().slideToggle(1000)  //The drop-down and disappearance of the menu are realized through replacement
		})
	</script>
</html>

10, Add, delete, modify and query

1. Increase

//Add tags in js
//First: string form div.innerHtml = 'here is the label';
//The second is to create a label var P = document createElement('p');
		Then add to div in    div.appendChild(p);
//==================
//Add labels in jq
//The first kind: $('div ') HTML ('write tag here ')
//Second: want to create the tag var P = $('< p > hahaha < / P >')
		Then add to div in		$('div').append(p);   //You can also use prepend, after, before

2. Change

//Modify the tag parent element in js Replacechild (child element, new element)
Get the child element and parent element first      var div = document.getElementById('div');
						var p = document.getElementById('p')
Creating a new element    var p1 = document.createElement('div')
And then          div.replaceChild(p,p1);
//Modify the element whose label is replaced in jq Replacewith (new element) = = = > note that all elements here are jq objects

3. Delete

//Parent element in js Removechild (child element)
//Elements in jq remove();     Element empty()

4. Hierarchical relationship acquisition node

//Native js
//Find parent node and child node parentNode find child node parent node childNodes
//firstElementChild     lastElementChild
//nextELementSibling	prevElementSibling

11, jQuery node operation

1. Create node

document.createElement()

//$(htmlstr)
//Htmlstr: node in HTML format
$('<p>Hello</p>');

2. Add node

append	appendTo	Insert content at the end of the selected original	father.append(son)		son.appendTo(father)
prepend	prependTo	Insert content at the beginning of the selected element		father.prepend(son)	son.prependTo(father)
before	insertBefore	Insert content after the selected element		after.before(front)	front.insertBefore(after)
after	insertAfter	Insert content before the selected element		front.after(after)	after.insertAfter(front)
These are two ways of writing. It is recommended to remember the one in front

3. Clearing and deleting nodes

  • empty: clear all elements of the specified node and keep them (recommended, which will clear the events bound on the child elements)
$('div').empty();
  • remove: compared with empty, it can be deleted by itself
$('div').remove();

4. Clone node

  • Role: copy matching elements
//Assign $(selector) all matched elements (deep copy)
//CloneNode (true) / / the original JS cloneNode does not pass parameters. Clone the tag itself and pass the parameter true
/

12, jQuery tools and methods

1. Array and object operations

1.1,$.inArray(value,array,[fromIndex])

Determine the position where the first parameter appears for the first time in the array and count from 0 (if it is not found, it will return - 1);

value: used to find whether there exists in the array

Array: array to be processed

fromIndex: used to search the array queue. The default value is 0. Search from the subscript

$.inArray(1,[1,2,3,1]);//Find the position of value in arr and return the subscript that appears for the first time. If it is not found, return - 1;
$.inArray(1,[1,2,3,1],2);//Start with subscript 2 (including subscript 2), find the position of value in arr, return the subscript that appears for the first time, and return - 1 if it is not found;

1.2 $(selector) toArray(), restore all Dom elements of jQuery set into an array

Assemble the inner number into a real array, remove the attribute, and only contain the label

$('div').toArray()

1.3,$. merge(first,second); Merge arrays;
$.merge([1,2,3,4],[5,6,7,8]);

1.4,$. parseJson(str); Parse JSON string as an object, which is equivalent to JSON parse(str);
1.4.1. JSON is a data format: the format is described by key value pairs

json usage: it is usually used to exchange data between different websites or languages

//json object format
var obj = {
	"age":30,
	"sex":"male"
}
//JSON string format
var str = '{
	"age":30,
	"sex":"male"
}'
$.parseJSON('{"name":"zhangshangfeng","age":"30"}');
1.5,json.stringify(obj) converts an object to a string (native)

2. String operation

2.1,$. trim(str) removes the spaces on both sides of the string and waits for str.trim()
$.trim('   1111 2222 33333     ');

3. Judgment type operation

$.type(obj)	Judge data type	typeof
$.isArray(obj) Determine whether it is an array  obj instanceof Array
$.isFunction(obj)	Determine whether it is a function obj instanceof function
$.isEmptyObject(obj)	Determine whether it is an empty object
$.isNumber(obj)		Determine whether it is a number (number type or string type)
$.isPlainObject(obj)   Judge whether it is pure object (face-to-face quantity syntax){} Or instantiation new  Constructor defined object)

13, Plug in

1. jQuery plug-in development syntax

1.1. Two ways to add methods to jQuery
$.method = fn; Static method
$.fn.method = fn  Example method    method It's your own name
//Instance method calls can only be called on jq objects

1.2. Batch extension instance method
	// Batch extension instance method
	$.fn.extend({
		f1:function(){
			return 100;
		},
		f2:function(){
			return 200;
		}
		})

Note: when you write your own plug-in, you usually open a separate JS file, named extend js

2. Common plug-ins

2.1 plug-in layer of pop-up layer

Layer pop-up layer component - jQuery pop-up layer plug-in (layui.com)

2.2 magnifying glass plug-in jqzoom

Address: jQuery zoom

2.3. Plug in of rotation chart
  • http://sorgalla.com/jcarousel/
  • https://github.com/OwlCarousel2/OwlCarousel2/
2.4. Image loading

Keywords: JQuery

Added by Peuplarchie on Fri, 28 Jan 2022 05:32:42 +0200