我只想知道,当您在按钮调用的函数中使用$(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>我试图改变我的span的html。
$(this).prev('span.fileError').html();
$(this).closest('div').find('span.fileError').html();
$(this).closest('div').find('span.fileError').text();
我试过的链接:
我已经看了更多的地方,我想我只会给那些我发现的最具启发性的地方看。在这里我需要做些什么,以及$(this)在函数中指的是什么?
发布于 2018-09-14 09:30:59
它是指按钮元素,还是指函数本身。
在jQuery事件处理程序函数中,this引用DOM元素本身,$(this)将其封装在jQuery对象中。
但是,对于如何更改span的HTML的问题,真正的答案将取决于什么是fileupload。
发布于 2018-09-14 09:45:47
这取决于您将使用什么样的函数作为事件处理程序:
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>
https://stackoverflow.com/questions/52328936
复制相似问题