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

jef*_*ack 2 javascript jquery stoppropagation

我不明白为什么,当使用stopPropagation()stopDefault()使用jQuery时,你必须在事件处理函数中向回调引入一个参数.浏览器如何知道传递给该函数的内容?另外,为什么不使用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");
  });
});
Run Code Online (Sandbox Code Playgroud)

对我来说,这样会更有意义.请注意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");
  });
});
Run Code Online (Sandbox Code Playgroud)

Mar*_*tin 8

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

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

$('a').on('click', function () {
   console.log(this);
});
Run Code Online (Sandbox Code Playgroud)

您将在控制台中看到已<a>单击的标记.这适用于DOM click事件和jQuery.你也可以看到这个<a>标签event.target.*

如果您需要有关该事件的信息,那么您需要将其注入到您的函数中,就像您在问题中所做的那样:

$('a').on('click', function (event) {
    console.log(event);
});
Run Code Online (Sandbox Code Playgroud)

这样,您就可以找到所有的活动信息event.同样,由于元素不在任何地方传播,因此您将停止传播事件本身是合乎逻辑的.

话虽这么说,this而且event.target一样