Javascript - 在函数中使用 return 不会终止函数

Javascript - Using return in function doesn't terminate function

我正在创建自己的 HTML5 视频播放器并将其打包为可重复使用的 jQuery 插件。我需要中途终止一个函数,因为当我按下播放键时,播放器会播放,然后自己暂停,如果之后创建播放器的次数为奇数。

HTML 控制集标记(使用 javascript 插入)

<div class="meo">
    <video>
        <source src="example.mp4">
        <source src="example.webm">
    </video>
    <ul>
        <li class="playp"></li> <!-- Ignore everything between here -->
        <li class="ctime"></li>
        <li class="progr">
            <div class="progb"></div>
        </li>
        <li class="ttime"></li>
        <li class="fs"></li> <!-- and here -->
    </ul>
</div>

Javascript

$.fn.meo = function() {
    return this.each(function() {
        var vid = $(this);
        var playp = $(".meo .playp");
        vid.wrap('<div class="meo"></div>');
        vid.after('<ul><li class="playp"></li><li class="ctime"></li><li class="progr"><div class="progb"></div></li><li class="ttime"></li><li class="fs"></li></ul>');

        $.fn.handlePlay = function() {
            var video = $(this).parent().siblings().get(0); // Getting the correct video element
            alert(video); // To show value of "video" (Returns multiple times depending on how many of the controlsets as above are found (This is not what I want))
            if (video.paused || video.ended) { // Testing if the video is playing
                video.play(); // After this I want to prevent the rest of the function executing
                return;
            } else {
                video.pause();
                return; // Terminate function
            };
        };

        playp.click(function(e) {
            $(this).handlePlay();
        });
    });
});

请帮忙。谢谢!

playp.click(function(e) {
   $(this).handlePlay();
});

这将在每次 $.each() 迭代时设置一个点击事件处理程序。这意味着 handlePlay() 将被调用多次,即使您只单击一个元素一次。

要么使用委托的事件处理程序,要么只使用新创建的元素来附加事件处理程序

委托事件:使用静态父元素将事件处理程序应用于

$(document).on("click",".meo .playp",function(){
  $(this).handlePlay();
});
$.fn.meo = function() {...};

或者在新创建的元素本身上设置事件

vid.find(".playp").click(function(){
    $(this).handlePlay();
});

此外,您也不需要每次都在 this.each() 中创建 $.fn.handlePlay,这样就可以将其移出它。

 $.fn.handlePlay = function() { ... }
 $.fn.meo = function() { ... }