最接近jQuery无法正常工作(closest in jQuery not working)

编程入门 行业动态 更新时间:2024-10-27 07:17:09
最接近jQuery无法正常工作(closest in jQuery not working)

当用户点击.dropzone-upload-btn元素时,我尝试通过jQuery点击.dropzone类。 我有这个代码,但它没有做任何事情。 知道为什么吗?

<div class="dropzone-wrapper"> <div class="dropzone"></div> <div class="dropzone-upload-btn"></div> </div>

这是jQuery代码(简化)

$('.dropzone-upload-btn').on("click", function() { return $(this).closest('.dropzone').click(); });

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>

And this is the jQuery code (simplified)

$('.dropzone-upload-btn').on("click", function() { return $(this).closest('.dropzone').click(); });

最满意答案

closest看匹配的元素及其祖先。 你可能想要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 :

$('.dropzone-upload-btn').on("click", function() { return $(this).prev('.dropzone').click(); });

参考文献:

http://api.jquery.com/prev/ http://api.jquery.com/prevAll/

如果您知道目标元素将在匹配的元素之前,但不一定在之前,则可以使用prevAll 。 prev只会看到第一个 眼前的兄弟姐妹。

prevAll和siblings之间的区别在于siblings姐妹在匹配元素之前之后查看兄弟姐妹,而prevAll只关注它之前的兄弟姐妹。

closest looks at the matched element and its ancestors. You probably want siblings:

$('.dropzone-upload-btn').on("click", function() { return $(this).siblings('.dropzone').click(); });

References:

http://api.jquery.com/closest/ http://api.jquery.com/siblings/

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(); });

References:

http://api.jquery.com/prev/ http://api.jquery.com/prevAll/

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.

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.

更多推荐

本文发布于:2023-08-03 06:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1384105.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:无法正常   最接近   工作   working   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!