如何将多个javascript对象实例绑定到元素

时间:2017-06-15 19:20:52

标签: javascript jquery

我正在尝试创建一个JavaScript播放器,但不确定如何在同一页面中拥有多个实例,以便每个实例都具有其功能



$(function() {
  var player = function(obj) {
    player.item = obj;
    player.audio = player.item.attr('data-player-src');
    player.audioElement = document.createElement('audio');
    player.audioElement.setAttribute('src', player.audio);
    player.audioElement.addEventListener('canplay', function() {
      player.item.find('.length').text('duration : ' + player.audioElement.duration + ' seconds');
    });
    player.audioElement.addEventListener('timeupdate', function() {
      player.item.find('.duration').text('current seconds : ' + player.audioElement.currentTime);
    });
    player.item.find('.play').on('click', function() {
      player.play();
    });
    player.item.find('.pause').on('click', function() {
      player.pause();
    });
    player.play = function() {
      player.audioElement.play();
    }
    player.pause = function() {
      player.audioElement.pause();
    }
    return player;
  }

  $.fn.player = function(options) {
    return player($(this));
  }

  var playerone = $("#player1").player();
  var playerone = $("#player2").player();
});

.player {
  border: 1px solid red;
  height: 60px;
  width: 200px;
  margin: 8px;
  padding: 8px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="player" id="player1" data-player-src="http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3">
  <div class="length">Length</div>
  <div class="duration"></div>
  <input type="button" class="play" value="Play" />
  <input type="button" class="pause" value="Pause" />
</div>

<div class="player" id="player2" data-player-src="https://www.soundjay.com/free-music/sounds/midnight-ride-01a.mp3">
  <div class="length">Length</div>
  <div class="duration"></div>
  <input type="button" class="play" value="Play" />
  <input type="button" class="pause" value="Pause" />
</div>
&#13;
&#13;
&#13;

目前按下player1的按钮会触发播放器2,反之亦然。 如何让每个玩家在同一页面中彼此独立

1 个答案:

答案 0 :(得分:0)

你只需要添加

$(function() {
  var player = function(obj) {
    var player={};//this line

进入函数的第一行,使其可重用。要通过jquery使它可用,你可以这样做:

$.fn.player=function(options){
  return player($(this));
}

USECASE

var playerone= $("#el").player();