简体   繁体   English

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

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

I would just like to know what $(this) refers to when you use it within a function called by a button. 我只想知道$(this)在按钮调用的函数中使用时指的是什么。

Is it referring to the button element or is it referring to the function itself. 它是指按钮元素还是功能本身。

Code example: 代码示例:

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

Things I have tried to change the html of my span 我试图改变我的跨度的HTML的事情

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

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

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

Links I have tried: 我尝试过的链接:

Jquery:find input field closest to button jQuery:查找最接近按钮的输入字段

Understand javascripts 'this' with clarity 清楚地理解javascript'this'

Finding Closest p tag to the clicked button 查找单击的按钮最近的p标签

I have look at more places, thought I would just show those I found most informing. 我看了更多地方,以为我只想展示我发现最多的信息。 What do I need to do here and to what $(this) is referring within the function? 我在这里需要做什么,以及函数中$(this)指的是什么?

Is it referring to the button element or is it referring to the function itself. 它是指按钮元素还是功能本身。

In jQuery event handler functions, this refers to the DOM element itself, and $(this) wraps that in a jQuery object. 在jQuery事件处理函数中, this是指DOM元素本身,而$(this)将其包装在jQuery对象中。

But the real answer to your question of how to change the HTML of your span is going to depend on what fileupload is. 但是,有关如何更改fileupload HTML的问题的真正答案将取决于文件fileupload是什么。

It depends on what kind of function will you use as event handler: 这取决于您将使用哪种函数作为事件处理程序:

  • arrow function takes this from the outer scope 箭头功能从外部范围获取
  • normal function has this assigned to a current element when used as an event handler. 普通函数在用作事件处理程序时已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