search
HomeWeb Front-endJS TutorialA brief discussion on event bubbling, event delegation, and jQuery element node operations

This article mainly brings you a brief discussion of event bubbling, event delegation, jQuery element node operations, wheel events and function throttling. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

1. Event bubbling definition

Event bubbling refers to triggering a certain type of event (such as a click onclick event) in an object. If the object defines a handler for this event, then This event will call this handler. If this event handler is not defined or the event returns true, then this event will be propagated to the parent object of this object, from the inside out, even if it is processed (all similar events of the parent object will be activated), or it reaches the top level of the object hierarchy, which is the document object (window in some browsers).

2. The role of event bubbling

Event bubbling allows multiple operations to be processed centrally (add event handlers to a parent element to avoid adding event handlers to multiple on child elements), it also allows you to capture events at different levels of the object layer.

3. Prevent event bubbling

The event bubbling mechanism is sometimes unnecessary and needs to be blocked. Use event.stopPropagation() to prevent it

4. Block default behavior

For example: block right-click menu

##5. Merge blocking operation

Actual development In , it is generally written to combine preventing bubbling and preventing default behavior. The combined writing is as follows:

6. Event delegation

Event delegation uses bubbling The principle is to add events to the parent, determine the subset of event sources, and perform corresponding operations. Event delegation can first greatly reduce the number of event bindings and improve performance; secondly, it can also allow newly added child elements to have Same operation.

1. How to write general binding events:

2. How to write event delegation: (In actual development, if a large number of sub-elements are operated event delegation should be used to improve performance)

7. Cancel event delegation

Usage: $("delegate object").undelegate( )

8. jQuery element node operation 1. Create node

## 2. Insert node

a. append() and appendTo() insert element

from behind inside the existing element. The output result is:

 

 b, prepend() and prependTo() Insert the element from the front inside the existing element

 

Output result:

 

 c, after() and insertAfter() Insert elements from behind outside the existing elements

 

 Output Result:

 

 d, before() and insertBefore() Insert the element from the front outside the existing element

 

Output result:

3. Delete node

$(selector).remove();

4. To do list (plan list) example

nbsp;html>


 <meta>
 <link>
 <style>
  .con{
   width:360px;
   margin:30px auto;
  }
  .con > h3{
   margin-bottom:15px;
  }
  .con input{
   width:290px;
   height:30px;
  }
  .con button{
   width:60px;
   height:34px;
   border:0;
  }
  .con ul li{
   display: flex;
   margin-top:15px;
   border-bottom:1px solid #ccc;
   justify-content: space-between;
  }
  .con li p{
   /*清除a元素之间的间隙*/
   font-size:0;
  }
  .con li p a{
   color:#1b5fdd;
   font-size:16px;
   margin-left:10px;
  }
  /*弹框样式*/
  .pop_con{
   position:fixed;
   top:0;
   right:0;
   bottom:0;
   left:0;
   background:#000;
   display: none;
  }
  .pop{
   width:400px;
   height:220px;
   position:absolute;
   left:50%;
   margin-left:-200px;
   top:50%;
   margin-top:-150px;
   background:#fff;
  }
  .pop .pop_title{
   padding:15px;
   display: flex;
   justify-content: space-between;
  }
  .pop .pop_title a{
   width:36px;
   height:36px;
   line-height:36px;
   border-radius:50%;
   background:#c7254e;
   color:#fff;
   text-align: center;
   position:absolute;
   top:-18px;
   right:-18px;
   transition: all 1s ease;
  }
  .pop_title h3{
   letter-spacing: 2px;
   font-weight: normal;
  }
  .pop_title a:hover{
   transform: rotate(360deg);
  }
  .pop_message{
   height:110px;
   line-height:110px;
   text-align: center;
  }
  .pop_confirm{
   height:36px;
   text-align: center;
  }
  .pop_confirm button{
   height:36px;
   line-height: 36px;
   padding:0 15px;
   background: #c7254e;
   border:none;
   color:#fff;
   outline: none;
  }
 </style>
 <script></script>
 <script>
  $(function(){
   //声明变量
   var $input = $("#input");
   $(".pop").click(function(){
    return false;
   });
   $(".pop_confirm").click(function(){
    $(".pop_con").fadeOut();
   });
   $(".close").click(function(){
    $(".pop_con").fadeOut();
   });
   $(".pop_con").click(function(){
    $(this).fadeOut();
   });
   //点击增加按钮,新增元素
   $("#add").click(function(){
    var $inputVal = $input.val();
    //如果输入值为空,出现弹框提示
    if($inputVal == ""){
     $(".pop_con").fadeIn();
     return false
    }
    $input.val("");
    var $li = $("<li><h3>"+$inputVal+"<p><a class=&#39;delete&#39; href=&#39;javascript:void(0);&#39;>删除<a class=&#39;prev&#39; href=&#39;javascript:void(0);&#39;>上移<a class=&#39;next&#39; href=&#39;javascript:void(0);&#39;>下移");
    $("ul").append($li);
   });
   //使用事件委托写在一起,提高性能
   $("ul").delegate("li a","click",function(){
    //首先判断点击的是哪个a
    if($(this).attr("class") == "prev"){
     //判断是否存在该元素
     if($(this).closest("li").prev().length ==0){
      $(".pop_message").html("已到顶部!");
      $(".pop_con").fadeIn();
      return false
     }
     $(this).closest("li").prev().before($(this).closest("li"));
    }else if($(this).attr("class") == "next"){
     if($(this).closest("li").next().length ==0){
      $(".pop_message").html("已到底部!");
      $(".pop_con").fadeIn();
     }
     $(this).closest("li").next().after($(this).closest("li"));
    }else{
     $(this).closest("li").remove();
    }
   })
  })
 </script>


 <p>
  </p><h3 id="To-do-list">To do list</h3>
  <input>
  <button>增加</button>
  
       
  •     

    学习html

        

         删除      上移      下移     

       
  •    
  •     

    学习css

        

         删除      上移      下移     

       
  •    
  •     

    学习ps

        

         删除      上移      下移     

       
  •   
   

  

   

    

提示信息

    X        

输入框不能为空

   

        

     9. Wheel events and function throttling 1. Use of jquery.mousewheel plug-in

jquery中没有滚轮事件,原生js中的鼠标滚轮事件不兼容,可以使用jquery的滚轮事件插件jquery.nousewheel.js。

2、函数节流

javascript中有些事件的触发频率非常高,比如onresize事件(jq中是resize),onmousemove事件(jq中是mousemove)以及上面说的鼠标滚轮事件,在短时间内多次触发执行绑定的函数可以巧妙的使用定时器来减少触发的次数,实现函数节流。

3、整屏滚动实例

nbsp;html>


 <meta>
 <title>整屏滚动</title>
 <link>
 <style>
  .page_con{
   width:100%;
   /*必须是固定定位,否则会有问题*/
   position:fixed;
   top:0;
   left:0;
   overflow: hidden;
  }
  .page{
   position:relative;
  }
  .page .main_con{
   width:900px;
   height:400px;
   position:absolute;
   left:50%;
   top:50%;
   margin-top:-200px;
   margin-left:-450px;
  }
  .page .main_con .left_img{
   width:363px;
   height:400px;
  }
  .page .main_con .left_img,.page .main_con .right_img{
   opacity: 0;
   position: relative;
   filter:alpha(opacity = 0);
   transition:all 1s ease 300ms;
  }
  .page .main_con .right_info{
   width:500px;
   height:300px;
  }
  .page .main_con .right_info,.page .main_con .left_info{
   font-size:20px;
   line-height:50px;
   color:#666;
   text-indent:2em;
   text-align:justify;
   position:relative;
   opacity:0;
   filter:alpha(opacity=0);
   transition:all 1000ms ease 300ms;
  }
  .main_con .right_img{
   width:522px;
   height:400px;
   top:-50px;
  }

  .main_con .left_info{
   width:350px;
   height:300px;
   bottom:-50px;
  }
  .main_con .left_img,.main_con .left_info{
   left:-50px;
  }
  .main_con .right_img,.main_con .right_info{
   right:-50px;
  }
  .main_con .center_img{
   opacity: 0;
   filter:alpha(opacity = 0);
   text-align: center;
   transition: all 1s ease 300ms;
  }
  .moving .main_con .left_img,.moving .main_con .left_info,.moving .main_con .center_img{
   left:0;
   opacity: 1;
   filter:alpha(opacity = 100);
  }
  .moving .main_con .center_img{
   transform: scale(0.8);
  }
  .moving .main_con .right_info,.moving .main_con .right_img{
   margin-top:50px;
   right:0;
   opacity: 1;
   filter:alpha(opacity = 100);
  }
  .moving .main_con .right_img{
   /*top:25px;*/
  }
  .page1{
   background:orange;
  }

  .page2{
   background:lightgreen;
  }
  .page3{
   background:cyan;
  }
  .page4{
   background:pink;
  }
  .page5{
   background:lightblue;
  }
  .points{
   width:16px;
   height:176px;
   position:fixed;
   top:50%;
   right:20px;
   margin-top:-88px;
  }
  .points li{
   width:16px;
   height:16px;
   line-height:16px;
   margin-top:15px;
   border:1px solid #666;
   border-radius:50%;
  }
  .points li:hover,.points li.active{
   width:6px;
   height:6px;
   cursor: pointer;
   border:6px solid #fff70c;
  }
 </style>
 <script></script>
 <script></script>
 <script>
  $(function(){
   $(".page1").addClass("moving");
   var page = $(".page");
   var len = page.length;
   var currentPage = 0;
   var timer = null;
   //获取显示区域的高度
   var $h = $(window).height();
   page.css({height:$h});
   $(window).mousewheel(function(event,dat){
    //向下滑dat为-1,向上滑dat为1
    //清除前面开的定时器,实现函数节流
    clearTimeout(timer);
    timer = setTimeout(function(){
     if(dat == -1){
      currentPage++;
      if(currentPage>len-1){
       //如果大于4的话,就不往下滑
       currentPage=len-1;
      }
     }else{
      currentPage--;
      //判断当前所在页是否小于0,如果小于就不往上滑。
      if(currentPage<0){
       currentPage=0;
      }
     }
     $(".page").eq(currentPage).addClass("moving").siblings().removeClass("moving");
     $("ul li").eq(currentPage).addClass("active").siblings().removeClass("active");
     $(".page_con").animate({top:-$h*currentPage},300);
    },200);

   });
   $(".points").delegate("li","click",function (){
    $(".page").eq($(this).index()).addClass("moving").siblings().removeClass("moving");
    $(this).addClass("active").siblings().removeClass("active");
    currentPage = $(this).index()+1;
    //首先判断下点击的元素在当前选中的元素的上面还是下面,如果是在上面的话,top值为正值,否则为负值。
    if($(this).index()<$(".active").index()){
     $(".page_con").animate({top:$h*$(this).index()});
    }else{
     $(".page_con").animate({top:-$h*$(this).index()});
    }
   })
  })
 </script>


<p>
 </p><p>
  </p><p>
   </p><p>
    <img  src="/static/imghwm/default1.png" data-src="../images/001.png" class="lazy" alt="A brief discussion on event bubbling, event delegation, and jQuery element node operations" >
   </p>
   <p>
    Web前端开发是从网页制作演变而来的,名称上有很明显的时代特征。在互联网的演化进程中,网页制作是Web1.0时代的产物,那是网站的主要内容都是静态的,用户使用网站的行为也以浏览为主。
   </p>
  
 
 <p>
  </p><p>
   </p><p>
    2005年以后,互联网进入web2.0时代,各种类似桌面软件的Web应用大量涌现,网站的前端有此发生了翻天覆地的变化。网页不再只是承载单一的文字和图片,各种富媒体让网页的内容更加生动,网页上的软件化的交互形式为用户提供了更好的使用体验,这些都是基于前端技术实现的。
   </p>
   <p>
    <img  src="/static/imghwm/default1.png" data-src="../images/002.png" class="lazy" alt="A brief discussion on event bubbling, event delegation, and jQuery element node operations" >
   </p>
  
 
 <p>
  </p><p>
   </p><p>
    <img  src="/static/imghwm/default1.png" data-src="../images/004.png" class="lazy" alt="A brief discussion on event bubbling, event delegation, and jQuery element node operations" >
   </p>
   <p>
    Web前端开发是从网页制作演变而来的,名称上有很明显的时代特征。在互联网的演化进程中,网页制作是Web1.0时代的产物,那是网站的主要内容都是静态的,用户使用网站的行为也以浏览为主。
   </p>
  
 
 <p>
  </p><p>
   </p><p>
    2005年以后,互联网进入web2.0时代,各种类似桌面软件的Web应用大量涌现,网站的前端有此发生了翻天覆地的变化。网页不再只是承载单一的文字和图片,各种富媒体让网页的内容更加生动,网页上的软件化的交互形式为用户提供了更好的使用体验,这些都是基于前端技术实现的。
   </p>
   <p>
    <img  src="/static/imghwm/default1.png" data-src="../images/003.png" class="lazy" alt="A brief discussion on event bubbling, event delegation, and jQuery element node operations" >
   </p>
  
 
 <p>
  </p><p>
   </p><p>
    <img  src="/static/imghwm/default1.png" data-src="../images/005.png" class="lazy" alt="A brief discussion on event bubbling, event delegation, and jQuery element node operations" >
   </p>
  
 

     
  •  
  •  
  •  
  •  

相关推荐:

如何实现Html事件冒泡

jquery阻止事件冒泡及其解决方法

有关javascript中事件冒泡和事件捕获机制

The above is the detailed content of A brief discussion on event bubbling, event delegation, and jQuery element node operations. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.