为什么stopPropagation在回调中使用事件参数,而不是使用'this'

why does stopPropagation take an event parameter in the callback instead of using 'this'?

本文关键字:this 参数 stopPropagation 回调 为什么 事件      更新时间:2023-09-26

我不明白为什么在使用jQuery的stopPropagation()stopDefault()时,你必须在事件处理函数的回调中引入一个参数。浏览器如何知道该向该函数传递什么?另外,为什么不使用this工作?

下面是有效的代码。我把容易混淆的部分加了黑体/星号:

$(document).ready(function() {
   $(".see-photos").on("click", function(**event**) {
    event.stopPropagation();
    $(this).closest(".tour").find(".photos").slideToggle();
  });
  $(".tour").on("click", function() {
    alert("This should not be called");
  });
});

对我来说,这样更有意义。注意,在处理程序函数中没有event参数用于回调。

$(document).ready(function() {
  $(".see-photos").on("click", function() {
    $(this).stopPropagation();
    $(this).closest(".tour").find(".photos").slideToggle();
  });
  $(".tour").on("click", function() {
    alert("This should not be called");
  });
});

这是因为jQuerys的.on()函数将触发事件的元素传递为this,而不是事件本身。

如果您尝试执行以下操作:

$('a').on('click', function () {
   console.log(this);
});

您将在控制台中看到被点击的<a>标签。这既适用于DOM click事件,也适用于jQuery事件。你也可以从event.target中看到这个<a>标签。*

如果你想要关于事件的信息,那么你需要将它注入到你的函数中,就像你在问题中所做的那样:

$('a').on('click', function (event) {
    console.log(event);
});

这样,所有的事件信息都可以在event中找到。同样,停止传播事件本身也是合乎逻辑的,因为元素没有在任何地方传播。

话虽如此,thisevent.target 不是相同的