jQuery中最接近的无法正常工作 [英] closest in jQuery not working
问题描述
当用户单击.dropzone-upload-btn
元素时,我尝试通过jQuery单击.dropzone
类.我有这段代码,但是它什么也没做.知道为什么吗?
I try to click on .dropzone
class through jQuery when users click on .dropzone-upload-btn
element. I have this code but it is not doing anything. Any idea why?
<div class="dropzone-wrapper">
<div class="dropzone"></div>
<div class="dropzone-upload-btn"></div>
</div>
这是jQuery代码(简体)
And this is the jQuery code (simplified)
$('.dropzone-upload-btn').on("click", function() {
return $(this).closest('.dropzone').click();
});
推荐答案
closest
查看匹配的元素及其祖先.您可能需要siblings
:
closest
looks at the matched element and its ancestors. You probably want siblings
:
$('.dropzone-upload-btn').on("click", function() {
return $(this).siblings('.dropzone').click();
});
参考文献:
- http://api.jquery.com/closest/
- http://api.jquery.com/siblings/
当然,如果您100%确定.dropzone
元素紧接在.dropzone-upload-btn
元素之前,则可以使用prev
或prevAll
:
Of course, if you're 100% sure the .dropzone
element will come immediately before the .dropzone-upload-btn
element, then you can use prev
or prevAll
:
$('.dropzone-upload-btn').on("click", function() {
return $(this).prev('.dropzone').click();
});
参考文献:
- http://api.jquery.com/prev/
- http://api.jquery.com/prevAll/
prevAll
. prev
只会查看 first immediate (先前的兄弟姐妹).
prevAll
can be used if you know the target element will come before the matched one, but not necessarily immediately before. prev
will only look at the first immediate previous sibling.
prevAll
和siblings
之间的区别是siblings
在匹配元素之前查看之前的兄弟姐妹,而在匹配元素之后查看的兄弟姐妹,而prevAll
仅查看其之前的兄弟姐妹.
The difference between prevAll
and siblings
is that siblings
looks at siblings before and after the matched element, while prevAll
looks only at the siblings before it.
这篇关于jQuery中最接近的无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!