jQuery:访问唯一父级中包含的唯一对象?

发布于 2024-12-26 09:52:07 字数 573 浏览 4 评论 0原文

假设以下布局:

<span class="container">
    <video class="video">
        <source ... />
    </video>
    <div class="controls">
        <div class="play">Play</div>
    </div>
</span>

使用 jQuery,我在文档加载上添加单击功能,如下所示:

$(document).ready(function() {

    $('.playpause').click(function() {

        var play = $(this);
        var video = ''; // D:

    });

});

假设页面上的视频数量或“控件”的子父对象的数量没有限制。这意味着我不想使用 $(this).parent().parent().find('.video')

Assume the following layout:

<span class="container">
    <video class="video">
        <source ... />
    </video>
    <div class="controls">
        <div class="play">Play</div>
    </div>
</span>

Using jQuery I'm adding a click function on document load, like so:

$(document).ready(function() {

    $('.playpause').click(function() {

        var play = $(this);
        var video = ''; // D:

    });

});

Assume there is no limit to the number of videos on the page or child parent objects of "controls". Meaning I don't want to use $(this).parent().parent().find('.video').

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

苏别ゝ 2025-01-02 09:52:07

最接近的方法 似乎很适合这里

$(this).closest('.container').find('.video');

The closest method seems like a good fit here

$(this).closest('.container').find('.video');
孤檠 2025-01-02 09:52:07
$(".video", $(this).parents(".container"))

应该有效。

$(".video", $(this).parents(".container"))

should work.

何以笙箫默 2025-01-02 09:52:07

您可以使用 prev() 函数 获取前一个元素,因此无论数量如何,这都会起作用父容器内的视频和/或控件元素...

var video = $(this).parent().prev();

细分...

$(this) 获取“play”类 div

.parent() 获取“ control" class div

.prev() 获取前一个元素(即匹配的“video”类 div)

这里是一个示例 JS Fiddle 来展示概念的工作原理

you can use the prev() function to get the previous element, so this will work regardless of the number of video and/or controls elements inside the parent container...

var video = $(this).parent().prev();

breakdown...

$(this) gets the "play" class div

.parent() gets the "controls" class div

.prev() get the previous element (i.e. the matching "video" class div)

here is a sample JS Fiddle to show the concept working

对你再特殊 2025-01-02 09:52:07

我只需在链接上添加一个包含视频参考的数据元素:

然后

var video = $(this).data('ref');

I'd just add an data element with the videos reference on the link:

Play

Then

var video = $(this).data('ref');
夜清冷一曲。 2025-01-02 09:52:07

像这样的东西:

var video = $('video', $(this).parentsUntil('span', '.container'));

Something like this:

var video = $('video', $(this).parentsUntil('span', '.container'));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文