I would just like to know what $(this)
refers to when you use it within a function called by a button.
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
$(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
Understand javascripts 'this' with clarity
Finding Closest p tag to the clicked button
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?
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.
But the real answer to your question of how to change the HTML of your span is going to depend on what fileupload
is.
It depends on what kind of function will you use as event handler:
this
assigned to a current element when used as an event handler. $('.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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.