javascript - jQuery 为什么回调函数中的 $(this) 是 "window"?

标签 javascript jquery dom window this

我正要为我的待办事项列表代码创建删除按钮。 这是我在 <script> 中的代码

  var del = $("<ion-icon name='trash'></ion-icon>").click((e)=>{
    var p = $(this).parent();
    p.remove()
    console.log(this)
  })

我在浏览器控制台中得到了这样的日志。

Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}

现在我发现另一种方法是使用$(e.target) 但我还是很好奇为什么回调函数中的 $(this) 是“window”。

我正在等待您的精彩答复:)谢谢!

  • 这就是我想在代码中执行的操作
$('#task').click((e)=>{

  var task = $("<li class='task'></li>").text($('#enter-task').val())

  var del = $("<ion-icon name='trash'></ion-icon>").click((e)=>{
    var p = $(this).parent();
    p.remove()
    console.log(this)
  })

  task.append(del)

  $("#tasklist").append(task)

})

最佳答案

jQuery .parent()方法返回 span 元素的父元素,如文档中所示。

您的图标可能位于 span 元素内,当您调用方法 Parent() var p = $(this).parent(); 您的目标是 Window对象。

关于javascript - jQuery 为什么回调函数中的 $(this) 是 "window"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59480353/

相关文章:

javascript - 如果未按下按钮,则在 30 秒内自动执行该功能

javascript - 自下而上的 jQuery Masonry

CSS 选择器获取前面的兄弟

java - 如何链接两个不同的元素

javascript - 为什么 clickHandler 没有更新状态?

javascript - 根据鼠标位置使用 Javascript 设置 CSS 'top' 属性

javascript - 创建过多 DOM 后页面挂起

javascript - 如何在 React 中通过引用获取可安装的 Prop 集

javascript - 浏览器在执行之前会加载整个 JavaScript block 吗?

javascript - 多方向视差滚动