jQuery initial knowledge and common events (1)

One, jQuery

1. jQuery is a JavaScript function library (framework).

2. jQuery is a lightweight "write less, do more" JavaScript library.

3. The jQuery library contains the following functions:

  • HTML element selection
  • HTML element manipulation
  • CSS operations
  • HTML event function
  • JavaScript special effects and animation
  • HTML DOM traversal and modification
  • AJAX
  • Utilities
    Tip: In addition, Jquery also provides a large number of plug-ins.

4. jQuery is currently the most popular js framework, and provides a large number of extensions.
5. jQuery has a powerful way to manipulate HTML elements and attributes, which is the ability to manipulate the DOM.
6.'$' is the abbreviation of jQuery, you can use $ or jQuery

Second, the entry function

jQuery entry function:
After all html tags (DOM) are loaded, it will be executed.

$(document).ready(function(){
    
    
    // 执行代码
});
或者
$(function(){
    
    
    // 执行代码
});

JavaScript entry function:
It will be executed after all content, including files such as external images, are loaded.

window.onload = function () {
    
    
    // 执行代码
}

Three, the selector

  • All selectors in jQuery start with a dollar sign: $()
  • jQuery selector "looks up" (or selects) HTML elements based on element id, class, type, attribute, attribute value, etc.
  • Element selector: $("p")
  • id selector: $("#test")
  • Class selector: $(".test")
  • Advanced options:
    $("*") select all elements
    $(this) select the current HTML element
    $("p.intro") select the p element whose class is intro
    $("p:first") select the first p element
    $("ul li:first") Select the first li element of the first ul element
    $("ul li:first-child") Select the first li element of each ul element
    $("[href]" ) Select elements with href attribute
    $("a[target='_blank']") Select all a elements whose target attribute value is equal to "_blank"
    $("a[target!='_blank']") Select all targets The a element whose attribute value is not equal to "_blank"
    $(":button") Select all input elements and button elements with type="button"
    $("tr:even") Select the tr element at an even position
    $("tr:odd ”) select tr elements at odd positions
Selector summary★
1.基本选择器
$("#id")            // ID选择器
$("div")            // 元素选择器
$(".classname")     // 类选择器
$(".classname,.classname1,#id1")     // 组合选择器

2.层次选择器
$("#id>.classname ")    // 子元素选择器
$("#id .classname ")    // 后代元素选择器
$("#id + .classname ")    // 紧邻下一个元素选择器
$("#id ~ .classname ")    // 兄弟元素选择器

3.过滤选择器(重点)
$("li:first")    // 第一个li
$("li:last")     // 最后一个li
$("li:even")     // 挑选下标为偶数的li
$("li:odd")      // 挑选下标为奇数的li
$("li:eq(4)")    // 下标等于 4 的li(第五个 li 元素)
$("li:gt(2)")    // 下标大于 2 的li
$("li:lt(2)")    // 下标小于 2 的li
$("li:not(#runoob)") // 挑选除 id="runoob" 以外的所有li

3.2内容过滤选择器
$("div:contains('Runob')")    // 包含 Runob文本的元素
$("td:empty")                 // 不包含子元素或者文本的空元素
$("div:has(selector)")        // 含有选择器所匹配的元素
$("td:parent")                // 含有子元素或者文本的元素

3.3可见性过滤选择器
$("li:hidden")       // 匹配所有不可见元素,或type为hidden的元素
$("li:visible")      // 匹配所有可见元素

3.4属性过滤选择器
$("div[id]")       		  // 所有含有 id 属性的 div 元素
$("div[id='123']")        // id属性值为123的div 元素
$("div[id!='123']")       // id属性值不等于123的div 元素
$("div[id^='qq']")        // id属性值以qq开头的div 元素
$("div[id$='zz']")        // id属性值以zz结尾的div 元素
$("div[id*='bb']")        // id属性值包含bb的div 元素
$("input[id][name$='man']") //多属性选过滤,同时满足两个属性的条件的元素

3.5状态过滤选择器
$("input:enabled")    // 匹配可用的 input
$("input:disabled")   // 匹配不可用的 input
$("input:checked")    // 匹配选中的 input
$("option:selected")  // 匹配选中的 option

4.表单选择器
$(":input")      //匹配所有 input, textarea, select 和 button 元素
$(":text")       //所有的单行文本框,$(":text") 等价于$("[type=text]"),推荐使用$("input:text")效率更高,下同
$(":password")   //所有密码框
$(":radio")      //所有单选按钮
$(":checkbox")   //所有复选框
$(":submit")     //所有提交按钮
$(":reset")      //所有重置按钮
$(":button")     //所有button按钮
$(":file")       //所有文件域
All selector reference☆

Novice Tutorial-Selector

Four, commonly used jQuery event methods

Event writing
$('selector').func(arg1,arg2,...);
// selector:某个元素
// func:事件函数
// arg1:参数,一般是事件函数的配置参数,和回调函数

Eg: jQuery uses events-hide the element after clicking it:

$("p").click(function(){
    
    
  $(this).hide();
});
  • $(document).ready(), equivalent to $() —— Execute after all tags (DOM) of html are loaded

  • Get the event object, which contains various useful information:

    $(document).ready(function(){
          
          
        $(window).keypress(function(event){
          
              
            //获取事件对象,里面包含各种有用的信息。
            console.log(event);
            //console.log(event.which);
        });
    });
    
Mouse event
  • click()-stand-alone element
  • dblclick()-double-click the element
  • mouseenter()-When the mouse pointer passes through the element, a mouseenter event occurs.
  • mouseleave() —— When the mouse pointer leaves the element, the mouseleave event will occur
  • mousedown() —— When the mouse pointer moves over the element and the mouse button is pressed, the mousedown event will occur
  • mouseup() —— When the mouse button is released on the element, the mouseup event will occur
  • hover()-cursor hover event
Element event
  • focus()-element (form) gets focus
  • blur()-element (form) loses focus
  • change() —— The change event occurs when the value of the element changes (only applicable to form fields)
  • submit() - When the form is submitted, the submit event will occur. This event only applies to form elements.
Keyboard events
  • keydown() —— Occurs when a key is pressed on the keyboard, it will be triggered continuously (except Opera browser) if it is pressed all the time, it returns the keyboard code;

  • .keyup() —— triggered when the user releases a key, as opposed to keydown, returns the keyboard code

  • .keypress() —— Occurs when a key is pressed on the keyboard and a character is generated, and the ASCII code is returned. Note: Pressing shift, alt, ctrl and other keys will not generate characters, so the monitoring is invalid. In other words, the keypress event will only be triggered when the key that can output characters on the screen is pressed. If you keep pressing a key, it will trigger continuously.

    Extension: keypress event to get typed characters

    $(window).keypress(function(event){
          
          
        //event.which是获取ASCII码,前面的函数是将ASCII码转换成字符,空格键和Enter键输出均为空白。
        console.log(String.fromCharCode(event.which));
        //从event对象中key属性获取字符,但是Enter键的key值为"Enter",空白键还是空白" "。
        console.log(event.key);
    });
    
Document/window events
  • load()-When the specified element is loaded, the load event will occur. This method is deprecated in jQuery version 1.8 .
  • resize() —— A resize event occurs when the browser window is resized.
  • scroll() —— When the user scrolls the specified element, a scroll event will occur.
  • unload()-Firefox and Chrome will block pop-up windows, so there is no way to see the effect.
    When the user leaves the page, the unload event occurs.
    When the following situations occur, the unload event will be triggered:
    click on a link to leave the page,
    type a new URL in the address bar,
    use the forward or back button to
    close the browser window,
    reload the page, and the

    unload() method stipulates that when the unload event occurs what happened.
    The unload() method only applies to window objects.
    Note: The unload event has different effects in different browsers. Please make sure to test this method in all browsers before using it. The unload() method was deprecated in jQuery version 1.8 and removed in version 3.0.
All event method reference☆

Novice Tutorial-Event Method

Five, effect events

  • Show and hide: hide, show, toggle

    $(selector).hide(speed,callback); Hide element
    $(selector).show (speed,callback); Show element
    $(selector).toggle(speed,callback);
    Optional parameter to switch the display/hide state of the element :
    Speed ​​—— execution time (slow, fast, ms)
    callback —— callback function
    details:
    1. (selector) the number of selected elements is n, when the callback function does not add parentheses, the callback function will be executed n times; When the callback function is added with parentheses, the function will be executed immediately, and will only be called once.
    2. Add parentheses after the callback function name, and the function body will be executed immediately, instead of waiting until the display/hide is completed;
    3. callback can be a function name, It can also be an anonymous function;

  • Fade in and fade out: fadeIn(), fadeOut(), fadeToggle(), fadeTo()

    $(selector).fadeIn(speed,callback); Fade in the hidden element
    $(selector).fadeOut(speed,callback); Fade out the visible element
    $(selector).fadeToggle(speed,callback); Switch the fade in and fade out state
    $ (selector).fadeTo(speed,opacity,callback); The gradient is the given opacity.
    Optional parameters:
    speed —— execution time (slow, fast, ms)
    callback —— callback function
    opacity —— opacity (value between 0 And 1)
    details:
    fadeTo() has no default parameters, slow/fast/ms must be added (time, in milliseconds)

  • 滑动:slideDown(),slideUp(),slideToggle()

    $(selector).slideDown(speed,callback); Slide down (show)
    $(selector).slideUp(speed,callback); Slide up (hide)
    $(selector).slideToggle(speed,callback); Switch status
    can be Optional parameters:
    speed —— execution time (slow, fast, ms)
    callback —— callback function

  • Custom animation: animate()

    The animate method allows you to create custom animations:
    $(selector).animate({params},speed,easing,callback);
    Alternate syntax (another parameter):
    (selector).animate({styles},{options })

    Mandatory parameters:
    {params}-mandatory parameters, used to form a specific css style, can be one or more style
    optional parameters:
    easing-specify the speed of elements in different points of the animation. The default value is "swing". Optional:
    "swing"-move slowly at the beginning/end, move fast in the middle
    "linear"-move at a constant
    speed, callback-Same as above
    example :

    	$("button").click(function(){
          
          
    	  $("div").animate({
          
          
    	    left:'250px',	// 新的左边距
    	    height:'toggle',	// 以高度为基准切换显示状态
    	    width:'+=150px'		// 增宽150px
    	  });
    	});
    
    	$("button").click(function(){
          
          
    	  var div=$("div");
    	  div.animate({
          
          left:'100px'},"slow");
    	  div.animate({
          
          fontSize:'3em'},"slow");
    	});
    

    Details:
    1. position : By default, all HTML elements have a static position and cannot be moved. If you need to manipulate the position, remember to first set the CSS position property of the element to relative , fixed, or absolute !
    2. Camel notation : When using animate() to set the new position style of an element (by passing parameters), all attribute names must be written in Camel notation, for example, paddingLeft must be used instead of padding-left and so on. This method can set almost all styles.
    3. Color animation : Color animation is not included in the core jQuery library. If you need to generate color animation, you need to download the color animation plug-in from jquery.com.
    4. Define the relative value : (The value is relative to the current value of the element). You need to add += or -= in front of the value. For example, make the element height 10 pixels: height:'+=10px'
    5. Use the predefined value : "show", "hide" or "toggle" to achieve the display and hide functions. Slow and fast have been predetermined to a specific value (xx milliseconds). Using these predefined values ​​is actually the same as using the values ​​directly.
    6. Queue execution: Using multiple animate() methods at the same time, jQuery will automatically call the Queue queue interface to place them in the queue for execution. The Queue queue interface is internally dedicated to animation services.
    Reason: JavaScript programming is almost always accompanied by asynchronous operations: setTImeout, css3Transition/Animation, ajax, dom drawing, postmessage, web Database, etc. The queue allows a series of functions to be called asynchronously without blocking the program, and remains asynchronous Synchronization (process lock).
    7. In- depth study of animation queue execution :

    • The animation chain is formed by multiple animate methods, then this animation chain will actually be added to the queue.
    • In each queue method, the animation data is written to the queue, and then the first sequence in the queue is taken out and executed by the dequeue method.
    • Write a process lock "inprogress" to the queue before starting execution, which means that the animation is still being executed, to prevent repeated execution of multiple animations in the same sequence. This is a processing solution for asynchronously executing synchronous collection.
    • At this point the animation begins. Note that the animation is a synchronous code that is executed asynchronously, and continues to call the next animate.
    • The same animate method logic is executed, but the problem arises at this time. The animation may be still executing but the subsequent animate is still calling, so at this time the subsequent animation code needs to wait (process lock).
    • There is an "inprogress" process lock at the head of the queue, so the animation only needs to be added to the queue at this time, but the execution can be judged by whether the inprogress exists.
    • All animate methods added to the queue are executed in sequence according to the above logic. After the animation is executed, there will be an end notification, and then the first queue is taken from the queue to continue execution, and so on.
      The above is the entire animation scheduling process. In fact, the queue is asynchronously idle and then the synchronous code is executed, so that there is no waste of resources in processing, and the accuracy is the highest.
  • Stop animation: stop()

    $(selector).stop(stopAll,goToEnd); —— Stop sliding, fade in and out and custom animation
    optional parameters :
    stopAll —— Whether the animation queue should be cleared. The default is false, that is, only active animations are stopped and any animation queued to be executed backwards.
    goToEnd —— Whether to complete the current animation immediately. The default is false.
    Details : An animation that is stopped immediately will not trigger a callback, and an animation that is completed immediately will trigger a callback.

  • jQuery-Chaining: Run multiple jQuery commands on the same element

    Advantages : the browser does not need to find the same element multiple times,
    eg : p1 tags execute css style changes, hide upwards, and display downwards

    	$("#p1").css("color","red").slideUp(2000).slideDown(2000);
    
Reference for all effect events☆

Novice Tutorial-Effect Event


Miscellaneous

1. jQuery maintenance: If the website contains many pages, and you want your jQuery function to be easy to maintain, then put the jQuery function in a separate .js file and import it through src.
2. Event: The page's response to different visitors is called an event, and jQuery is specially designed for event handling.
3. Event handling: Program refers to the method that is called when certain events occur in HTML.
4. jQuery dynamically generated elements: For elements dynamically generated by jQuery, common events such as click cannot be directly bound.
eg:

$(".box ").click(function(){
    
    });

Although the box class is generated, there is still no click event. The solution:

$(".box ").live('click', function(){
    
    });	// 不建议
// 或者:
$(".box ").on('click', function(){
    
    });	
// 另外 click, blur, keyup, change等方法,都可以这样解决。

Guess you like

Origin blog.csdn.net/GeniusXYT/article/details/103616220