Summary of some basic operations in jQuery

Foreword:

  • jQuery, as the name suggests, is JavaScript and Query. It is a js library to assist JavaScript development.
  • $ Is the core function of jQuery, which can accomplish many functions of jQuery. $() is to call the function $
  • The jQuery object is an array of dom objects + a series of functions provided by jQuery.
  • The jQuery object cannot use the properties and methods of the DOM object, and the DOM object cannot use the properties and methods of the jQuery object.
  • Convert dom object into jQuery object:
    $(DOM object) can be converted into jQuery object
  • Convert jQuery object to dom object
    jQuery object [subscript] Get the corresponding DOM object

1. DOM operation

1. DOM attribute manipulation

  • html()It can set and get the content in the start tag and end tag. DOM attribute with innerHTMLthe same.
  • text()It can set and get the text in the start tag and end tag. DOM attribute with innerTextthe same.
  • val()It can set and get the value attribute value of the form item. DOM attribute with valuethe same.

Example:

a.html() 	  //取出a的html值  
a.html(val)   //让a的html值变为val
a.text()	  //取出a的text值  
a.text(val)   //让a的文本值变为val
a.val()  	  //取出a的val值(input) 
a.val(v)  	  //设置a的value值为v 
//val实战举例:
// 操作单选
$(":radio").val(["radio2"]);
// 批量操作多选框的选中状态 
$(":checkbox").val(["checkbox3","checkbox2"]); 
// 操作单选的下拉框选中状态 
$("#single").val(["sin2"]);
// 批量操作多选的下拉框选中状态 
$("#multiple").val(["mul2","mul3","mul4"]);
  • attr()You can set and get the value of the attribute. It is not recommended to operate checked, readOnly, selected, disabled, etc.; the
    attr method can also operate on non-standard attributes. For example, custom attributes: abc, edf.
  • removeAttr('xxx') Remove the xxx attribute value.
  • prop() You can set and get the value of the attribute, only recommended operations checked, readOnly, selected, disabled, etc.
  • removeProp('xxx') Remove the xxx attribute value.

Example:

a.attr('name') //取出a的name值
a.attr("name","username") //把a的name值设置为username
a.attr("yushiwen","123")  //把a的自定义属性yushiwen的值设置为123
a.removeAttr('class')    //移除a的class属性
a.prop('id')  //取出a的id值
a.prop('id',"wh")  //设置a的id值为wh
a.removeProp('class')  //移除a的class属性

2. The difference between attr() and prop():

When the value of the checked attribute is obtained, if the checked attribute is set, as follows:
Insert picture description here

attr() will return checked, prop() will return true, as follows:
Insert picture description here
Insert picture description here
when the value of the checked attribute is obtained, if the checked attribute is not set, as follows:
Insert picture description here
attr() will return undefined, prop() will return false, as follows:
Insert picture description here
Insert picture description here
undefined in the end What is it? Officials think that returning undefined is an error, so we should use the prop() method when operating the checked property.
Similarly, the readOnly, selected, disabled, etc. attributes are the same as checked, and the prop() method should be used when operating on them.

3. Addition, deletion and modification of DOM

Internal insertion:

  • appendTo() , Such as a.appendTo(b) inserts a at the end of the child element of b and becomes the last child element
  • prependTo(), Such as a.prependTo(b) insert a in front of all child elements of b to become the first child element

External insertion:

  • insertAfter() , Such as a.insertAfter(b) to get ba
  • insertBefore(), Such as a.insertBefore(b) to get ab

replace:

  • replaceWith(), Such as a.replaceWith(b) replace a with b, note here is to replace a with b
  • replaceAll(), Such as a.replaceAll(b) replace all b with a

delete:

  • remove() , Such as a.remove(); delete a tag
  • empty() , Such as a.empty(); Clear the content in the a tag

2. CSS style operation

  • css() Read or write style attributes of matched elements
  • addClass() Add one or more class values ​​to the element
  • removeClass() Delete the style, delete the class value of the element; pass one or more specific class values, it will delete the specific one or more classes; not pass the value is to remove all the class values.
  • toggleClass() Perform the switch operation of adding/deleting the selected element. The switch is to delete if it has the type, and add it if it is not.
  • offset() Get and set the coordinates of the element.

Example:

a.css('color') //取出a元素的color
a.css('color',"red") //设置a元素的color为red
//实战演示
//addClass() - 向被选元素添加一个或多个类,下述示例添加多个
$('div:first').addClass("redDiv blackDiv");
//removeClass() - 从被选元素删除一个或多个类 ,下述示例删除多个,也就是所有class
$('div:first').removeClass();
//toggleClass() - 对被选元素进行添加/删除类的切换操作 ,切换就是如果具有该类那么删除,如果没有那么添加上
$('div:first').toggleClass("redDiv");
//offset() - 返回第一个匹配元素相对于文档的位置。
var os = $('div:first').offset();
//注意通过offset获取到的是一个对象,这个对象有两个属性top表示顶边距,left表示左边距
alert("顶边距:"+os.top+" 左边距:"+os.left);

//调用offset设置元素位置时,也需要传递一个js对象,对象有两个属性top和left
//offset({ top: 10, left: 30 });
$('div:first').offset({
    
    
	 top:50,
	 left:60
 }); 

Three. jQuery effect

1. Basic effect

  • show() Show hidden elements
  • hide() Hide the visible elements.
  • toggle() Hide when it is visible, and show it when it is not visible.

2. Sliding effect

  • slideDown() Method is used to slide the element down.
  • slideUp() Method is used to slide the element up.
  • slideToggle()The method can switch between the slideDown() and slideUp() methods. If the elements slide down, slideToggle() can slide them up. If the elements slide up, slideToggle() can slide them down.

3. Fade in and fade out effect

  • fadeIn() Fade in (slowly visible)
  • fadeOut() Fade out (slowly disappear)
  • fadeTo()Slowly modify the transparency to the specified value within the specified time. 0 transparent, 1 complete visible, 0.5 translucent
  • fadeToggle() Fade in/out switch

4. Common points of the above three sets of methods

All of the above methods can add parameters.

  • The first parameter is the duration of the animation, in milliseconds
  • The second parameter is the callback function of the animation (function automatically called after the animation is completed)

IV. $( function(){} )And window.onload = function(){}the difference

1. When are they triggered respectively?

  • $( function(){} )After the jQuery page is loaded, that is, the browser's kernel has parsed the tags of the page, and it will be executed immediately after the DOM object is created.
  • window.onload = function(){}It is after the native js page is loaded, that is, in addition to waiting for the browser kernel to parse the tag to create a DOM object, but also to wait for the content to be loaded when the tag is displayed. (Label such as iframe and img)

2.The order in which they are triggered?

  • $( function(){} )Is executed after the jQuery page is loaded
  • window.onload = function(){}Is after the native js page is loaded
  • In other words, execute earlier $( function(){} )thanwindow.onload = function(){}

3.How many times did they execute?

  • $( function(){} )After the jQuery page is loaded, all the registered function functions are executed in sequence.
  • window.onload = function(){}After the native js page is loaded, only the last assignment function will be executed.

4. Code demonstration:

Code:

<script type="text/javascript">

	$(function(){
    
    
		console.log(1);
	});

	$(document).ready(function () {
    
    
        console.log(2);
    });

    jQuery(function () {
    
    
        console.log(3);
    });

    window.$(function () {
    
    
        console.log(4);
    });

	window.jQuery(function () {
    
    
        console.log(5);
    });

	window.onload= function () {
    
    
        console.log(6);
    };

	onload = function (ev) {
    
    
        console.log(7);
	};


</script>

Output result:
Insert picture description here

Five. jQuery event operation

  • click()It can bind click events and trigger click events. Elements added later will not bind events
  • mouseover()The mouse moves into the event. Elements added later will not bind events
  • mouseout()The mouse moves out of the event. Elements added later will not bind events
  • bind()You can bind one or more events to the element at once. Elements added later will not bind events
  • one()The use is the same as bind. But the event bound to the one method will only respond once.
  • unbind() The opposite of the bind method, unbind the event
  • live()It is also used to bind events. It can be used to bind events of all elements matched by the selector. It works even if this element is dynamically created later

Example:

$("h5").click(function () {
    
     // 传function是绑定事件
	alert('h5单击事件 == click方法绑定')
});
$("h5").click(); // 不传function是触发事件
//鼠标移入
$("h5").mouseover(function () {
    
    
	console.log("你进来了")
});
//鼠标移出
$("h5").mouseout(function () {
    
    
console.log("你出去了")
});
// 给元素绑定事件,绑定事件可以链式操作
// jquery对象.事件方法(回调函数(){ 触发事件执行的代码 }).事件方法(回调函数(){ 触发事件执行的代码 }).事件方法(回调函数(){ 触发事件执行的代码 })
$(".head").click(function(){
    
    
	$(".content").toggle();
}).mouseover(function(){
    
    
	$(".content").toggle();
}); 
//jQuery提供的绑定方式:bind(type,[data],fn)函数把元素和事件绑定起来
//type表示要绑定的事件   [data]表示传入的数据   fn表示事件的处理方法
//bind(事件字符串,回调函数),后来添加的元素不会绑定事件
//使用bind()绑定多个事件   type可以接受多个事件类型,使用空格分割多个事件
$(".head").bind("click mouseover",function(){
    
    
	$(".content").toggle();
});
//one()只绑定一次,绑定的事件只会发生一次 one(type,[data],fn)函数把元素和事件绑定起来
//type表示要绑定的事件   [data]表示传入的数据   fn表示事件的处理方法
$(".head").one("click mouseover",function(){
    
    
	$(".content").toggle();
}); 
//live方法会为现在及以后添加的元素都绑定上相应的事件
$(".head").live("click",function(){
    
    
	$(".content").toggle();
});
$("#panel").before("<h5 class='head'>什么是jQuery?</h5>"); //之后动态添加元素

6. Event bubbling and javaScript event object

1. The bubbling of events

  • What is event bubbling?
    Event bubbling means that the parent and child elements listen to the same event at the same time. When the event of the child element is triggered, the same event is also passed to the event of the parent element to respond.
  • So how to prevent the event from bubbling?
    In the body of the child element event function, return false; can prevent the bubbling of the event.

2.javaScript event object

  • The event object is a javascript object that encapsulates the triggered event information. Our main concern is how to get this javascript event object. And use.
  • How to get the javascript event object?
    When binding an event to an element, add a parameter to the function( event) parameter list of the event. This parameter name is used to call it event. This event is the event object passed by javascript to the event handler.

2.1 Native javascript to get the event object

//原生javascript获取 事件对象
window.onload = function () {
    
    
	document.getElementById("areaDiv").onclick = function (event) {
    
    
		console.log(event);
	}
}

Output result:
Insert picture description here

2.2 jQuery code to get the event object

//JQuery代码获取事件对象
$(function () {
    
     
	$("#areaDiv").click(function (event) {
    
    
		console.log(event);
	});
});

Insert picture description here
You can see that the contents of the two are similar, except that the jQuery code acquisition event object wraps the native javascript acquisition event object.

2.3 Examples of event objects

Use bind to bind the same function to multiple events at the same time. How to get what event the current operation is

$("#areaDiv").bind("mouseover mouseout",function (event){
    
    
	if (event.type == "mouseover") {
    
    
		console.log("鼠标移入");
	} else if (event.type == "mouseout") {
    
    
		console.log("鼠标移出");
	}
});

Guess you like

Origin blog.csdn.net/MrYushiwen/article/details/113055377