将mouseenter和mouseleave事件绑定到具有相同类的多个元素

时间:2022-05-10 03:13:53

I have a number of elements div.teaser that each contain a video wrapped with mediaelementplayer. On mouseenter and mouseleave I want the video to play media.play and stop media.stop respectively.

我有一些div.teaser元素,每个元素都包含一个用mediaelementplayer包装的视频。在mouseenter和mouseleave上,我希望视频分别播放media.play和stop media.stop。

HTML looks like this:

HTML看起来像这样:

<div class="teaser">
    <a href="#">
       <video>...</video>
    </a>
</div>
<div class="teaser">
    <a href="#">
       <video>...</video>
    </a>
</div>
[... and so on]

The problem is that if I hover any of the elements they all fire the event. Current jquery is:

问题是,如果我悬停任何元素,他们都会触发事件。目前的jquery是:

$('video').mediaelementplayer({
    features: [],
    loop: false,
    enableAutosize: true,
    alwaysShowControls: false,
    iPadUseNativeControls: false,
    iPhoneUseNativeControls: false, 
    AndroidUseNativeControls: false,
    alwaysShowHours: false,
    showTimecodeFrameCount: false,
    pauseOtherPlayers: true,

    success: function(media, domElement, player) {      
        $(".teaser").on({
            mouseenter: function() {
                media.play();
            },
            mouseleave: function() {
                media.stop();
            }

        });

    } // Success     
}); // mediaelementplayer

At a guess I need to tell the function to bind to $(this) div.teaser. I've tried a number of options but none seem to stick.

猜测我需要告诉函数绑定到$(this)div.teaser。我尝试了很多选择,但似乎都没有。

JSFiddle

2 个解决方案

#1


2  

something like this:

像这样的东西:

$(".teaser").mouseenter(function(){
$(this).find('video').media.play();
});

you could show the html that would make it easier...

你可以显示更容易的HTML ...

EDIT: here you go

编辑:你走了

$(".teaser").mouseenter(function(){
$(this).find('video').get(0).play();
});

#2


0  

Supposed you have this div#video, which contains all these div.teaser. You can attach an event listener like this

假设你有这个div#video,其中包含所有这些div.teaser。您可以附加这样的事件监听器

$('#video').on('mouseenter', 'div.teaser', function() {
  //do media play
});

$('#video').on('mouseleave', 'div.teaser', function() {
  //do media stop
});

To get the div.teaser object use $(this) inside the function

要获取div.teaser对象,请在函数内使用$(this)

#1


2  

something like this:

像这样的东西:

$(".teaser").mouseenter(function(){
$(this).find('video').media.play();
});

you could show the html that would make it easier...

你可以显示更容易的HTML ...

EDIT: here you go

编辑:你走了

$(".teaser").mouseenter(function(){
$(this).find('video').get(0).play();
});

#2


0  

Supposed you have this div#video, which contains all these div.teaser. You can attach an event listener like this

假设你有这个div#video,其中包含所有这些div.teaser。您可以附加这样的事件监听器

$('#video').on('mouseenter', 'div.teaser', function() {
  //do media play
});

$('#video').on('mouseleave', 'div.teaser', function() {
  //do media stop
});

To get the div.teaser object use $(this) inside the function

要获取div.teaser对象,请在函数内使用$(this)