我想創建一個JavaScript的球員,但不知道怎樣纔可以有它的多個實例在同一個頁面,使得各有其上的功能我如何可以綁定多個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>
目前關於PLAYER1按鈕點擊就會觸發player2反之亦然。 我怎樣才能使獨立於彼此在同一個頁面
在jQuery中,要做到這一點最簡單的方法是通過創建一個插件。如果沒有jQuery,你必須使用'new'關鍵字來創建實例 – adeneo