jQuery中最接近的无法正常工作 [英] closest in jQuery not working

查看:89
本文介绍了jQuery中最接近的无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户单击.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元素之前,则可以使用prevprevAll:

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.

prevAllsiblings之间的区别是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆