开发者

Separating state of elements matching selector in jQuery plugins

开发者 https://www.devze.com 2023-04-12 15:50 出处:网络
Demo: http://jsfiddle.net/waitinforatrain/7Uzhg/2/ I\'m rewriting a jQuery plugin which displays subtitles from .srt files. The div that displays subtitles contains attributes data-video (the ID of t

Demo: http://jsfiddle.net/waitinforatrain/7Uzhg/2/

I'm rewriting a jQuery plugin which displays subtitles from .srt files. The div that displays subtitles contains attributes data-video (the ID of the associated HTML5 Video object) and data-srt (a URL that contains the subtitles file).

The idea is that if I write

$('.srt').srt();

This will load and play the subtitles from all elements with the class srt.

There is a method in the jQuery plugin called playSubtitles which does the main job. This has an integer currentSubtitle which holds the index of the current subtitle to be played.

The problem is that if $('.srt') matches more than one element, they will both share the currentSubtitle variable, and I'm n开发者_开发知识库ot sure how to separate those out.


you need to wrap your plugin code with each so every selector have their own copy of that variable:

$.fn.srt = function() {
   return this.each(function() {
       var currentSubtitle;
       var self = $(this);
       return $.extend(self, {
           playSubtitles: function(...) {
               ...
           }
       });
   });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号