首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解jQuery $(this).closest(元素);

理解jQuery $(this).closest(元素);
EN

Stack Overflow用户
提问于 2018-09-14 09:27:06
回答 2查看 564关注 0票数 1

我只想知道,当您在按钮调用的函数中使用$(this)时,它指的是什么。

它是指按钮元素,还是指函数本身。

代码示例:

代码语言:javascript
复制
<div>
<span class="fileError"></span>
<input type="file" class="understanding" />
</div>

<script>
$('.understanding').click(function(){

   $(this).closest('div').find('span.fileError').html('My brain needs help');
});
</script>

我试图改变我的span的html。

$(this).prev('span.fileError').html();

$(this).closest('div').find('span.fileError').html();

$(this).closest('div').find('span.fileError').text();

我试过的链接:

Jquery:查找最接近按钮的输入字段

清晰地理解javascripts 'this‘

查找与单击按钮最近的p标记

我已经看了更多的地方,我想我只会给那些我发现的最具启发性的地方看。在这里我需要做些什么,以及$(this)在函数中指的是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-14 09:30:59

它是指按钮元素,还是指函数本身。

在jQuery事件处理程序函数中,this引用DOM元素本身,$(this)将其封装在jQuery对象中。

但是,对于如何更改span的HTML的问题,真正的答案将取决于什么是fileupload

票数 4
EN

Stack Overflow用户

发布于 2018-09-14 09:45:47

这取决于您将使用什么样的函数作为事件处理程序:

  • 箭头函数从外部范围获取此信息。
  • 当使用普通函数作为事件处理程序时,将this分配给当前元素。

代码语言:javascript
复制
$('.understanding-arrow').click(() => {
  console.log(this === window && "this is window");

  $(this).closest('div').find('span.fileError').html('My brain needs help');
});
$('.understanding-normal').click(function() {
  console.log(this === $('.understanding-normal')[0] && "this is input el");

  $(this).closest('div').find('span.fileError').html('My brain needs help');
});
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span class="fileError"></span>
  <input type="button" class="understanding-arrow" value="arrow function" />
</div>
<div>
  <span class="fileError"></span>
  <input type="button" class="understanding-normal" value="normal function" />
</div>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52328936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档