管理Javascript文件中的事件传播

Managing Event Propagation in Javascript Files

本文关键字:事件 传播 Javascript 文件 管理      更新时间:2023-09-26

下面是两个相互交织的Javascript文件。我通常如何管理两个Javascript文件之间的事件传播?第一个js文件

var red = [0, 100, 63];
var orange = [40, 100, 60];
var green = [75, 100, 40];
var blue = [196, 77, 55];
var purple = [280, 50, 60];

var myName = "Prasanth Louis";
var letterColors=[red,orange,green,blue,purple];
if(10 > 3) {
    bubbleShape = "square";
}

else {
    bubbleShape = "circle";
}

drawName(myName, letterColors);
bounceBubbles();
$(document).ready(function(){
$('body').click(function()
{
$('body').load('index1.html')});
});

2nd js文件//在没有第一个js文件的情况下,这非常好

 var main = function() {
  $('.dropdown-toggle').click(function() {
    $('.dropdown-menu').toggle();
  });
  $('.arrow-prev').click(function(){
     var currentSlide=$('.active-slide')
     var prevSlide=currentSlide.prev()
      var currentDot = $('.active-dot');
  var prevDot = currentDot.prev();
     if(prevSlide.length==0)
     {
         prevSlide=$('.slide').last();
          prevDot = $('.dot').last();
     }

     currentSlide.fadeOut(600)
     currentSlide.removeClass('active-slide')
     prevSlide.fadeIn(600)
     prevSlide.addClass('active-slide')
      currentDot.removeClass('active-dot');
  prevDot.addClass('active-dot');
  });
  $('.arrow-next').click(function() {
    var currentSlide = $('.active-slide');
    var nextSlide = currentSlide.next();
var currentDot=$('.active-dot')
var nextDot=currentDot.next();

    if(nextSlide.length==0)
    {
        nextSlide=$('.slide').first();
        nextDot=$('.dot').first();
    }
     currentSlide.fadeOut(600).removeClass('active-slide');
    nextSlide.fadeIn(600).addClass('active-slide');
    currentDot.removeClass('active-dot')
nextDot.addClass('active-dot')
  });
}
$(document).ready(main);

您没有阻止第二个js文件中的事件传播,因此第二个.js文件中.arrow-prev上的事件和第一个js文件中body上的事件都将执行。这意味着body将被替换。我无法说出确切的行为,因为我不知道你的index1.html文件中有什么,但这是我能看到的唯一交互。

使用stopPropagation不允许浏览器同时捕获两个事件处理程序。

因此有两种事件传播方式:

  • 气泡

  • 捕获

有关更多详细信息,请查看此精彩的阅读

jQuery中,点击事件传播总是冒泡

气泡意味着点击事件被触发/从点击的元素传播到顶部父元素。你可以从内到外思考。

在您的情况下,当点击第二个js文件中的内部元素(如箭头prev/箭头next/…)时,它的事件处理程序首先被触发。然后最后触发正文的点击事件处理程序,这会重新加载页面并导致意外行为。

避免此问题的两种方法:

  1. 将event.stopPropagation添加到内部元素的事件处理程序

    Example: 
    $('.arrow-next').click(function(e) {
      ... // your existing codes
      // put a stop here to prevent event being handled by body
      e.stopPropagation();
    });
    
  2. 将以下检查添加到主体的点击事件

    $(document).ready(function(){
      $('body').click(function(){
        if(e.target==e.currentTarget){
        // this make sure that page is loaded only when 
        // body is clicked.
        $('body').load('index1.html')});
      }
    });