繁体   English   中英

了解jQuery $(this).closest(element);

[英]Understanding jQuery $(this).closest( element );

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

它是指按钮元素还是功能本身。

代码示例:

<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>

我试图改变我的跨度的HTML的事情

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

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

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

我尝试过的链接:

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

清楚地理解javascript'this'

查找单击的按钮最近的p标签

我看了更多地方,以为我只想展示我发现最多的信息。 我在这里需要做什么,以及函数中$(this)指的是什么?

它是指按钮元素还是功能本身。

在jQuery事件处理函数中, this是指DOM元素本身,而$(this)将其包装在jQuery对象中。

但是,有关如何更改fileupload HTML的问题的真正答案将取决于文件fileupload是什么。

这取决于您将使用哪种函数作为事件处理程序:

  • 箭头功能从外部范围获取
  • 普通函数在用作事件处理程序时已this分配给当前元素。

 $('.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'); }); 
 <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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM