我有一个页面显示一些带有播放按钮的图像。单击播放按钮时,我正在尝试将兄弟元素的src替换为相应gif的路径。出于某种原因,当我单击第一个元素上的播放按钮时,它工作正常。当我单击第二个元素上的播放时,它会交换第二个gif上的src,但也会重新启动第一个gif。如果我点击第三个播放按钮上的播放,它会从头开始重新启动所有3个GIF。
HTML看起来像这样:
<div class="player">
<div class="player--image">
<img class="gif--control gif--play" src="/img/play-button.png" />
<img class="player--gif" src="/assets/player-image.png" data-gif="/assets/player-gif.gif"/>
</div>
<div class="player--info">
<div class="player--name">
<h3 class="title">#23</h3>
<h3 class="title title__large">Player Name</h3>
<h3 class="title">Center</h3>
</div>
<div class="excerpt">
Lorem ipsum
</div>
</div>
</div>
<div class="player">
<div class="player--image">
<img class="gif--control gif--play" src="/img/play-button.png" />
<img class="player--gif" src="/assets/player-2-image.png" data-gif="/assets/player-2-gif.gif"/>
</div>
<div class="player--info">
<div class="player--name">
<h3 class="title">#45</h3>
<h3 class="title title__large">Player Name</h3>
<h3 class="title">Center</h3>
</div>
<div class="excerpt">
Lorem ipsum
</div>
</div>
</div>
Javascript / jQuery如下:
$(document).on('click tap', '.gif--control', function(){
var $this = $(this);
var $gif = $this.siblings('.player--gif');
var src = $gif.attr('data-gif');
$gif.attr('src', src);
});
我已尝试将唯一ID添加到已交换src的img元素中,但仍然会在单击新的播放按钮时重新启动所有gif。任何帮助将不胜感激 - 感觉我错过了一些非常简单的东西。
答案 0 :(得分:2)
您正在使用未引用的$sibling
电话;我用$gif
替换它,你的代码似乎运行正常。
$(document).on('click tap', '.gif--control', function(){
var $this = $(this);
var $gif = $this.siblings('.player--gif');
var src = $gif.attr('data-gif');
$gif.attr('src', src);
});
答案 1 :(得分:0)
您可以再使用一个解决方案https://jsfiddle.net/7jktzLw5/2/
$(document).on('click tap', 'img.gif--control', function(){
var $this = $(this);
var $gif = $this.next('img.player--gif');
$gif.attr('src', $gif.attr('data-gif'));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="player">
<div class="player--image">
<img class="gif--control gif--play" src="https://image.flaticon.com/icons/png/128/70/70776.png" />
<img class="player--gif" src="https://image.flaticon.com/icons/png/128/42/42829.png" data-gif="https://image.flaticon.com/icons/png/128/44/44382.png"/>
</div>
<div class="player--info">
<div class="player--name">
<h3 class="title">#23</h3>
<h3 class="title title__large">Player Name</h3>
<h3 class="title">Center</h3>
</div>
<div class="excerpt">
Lorem ipsum
</div>
</div>
</div>
<div class="player">
<div class="player--image">
<img class="gif--control gif--play" src="https://image.flaticon.com/icons/png/128/70/70776.png" />
<img class="player--gif" src="https://image.flaticon.com/icons/png/128/136/136369.png" data-gif="https://image.flaticon.com/icons/png/128/236/236540.png"/>
</div>
<div class="player--info">
<div class="player--name">
<h3 class="title">#45</h3>
<h3 class="title title__large">Player Name</h3>
<h3 class="title">Center</h3>
</div>
<div class="excerpt">
Lorem ipsum
</div>
</div>
</div>
&#13;
我已使用next
代替siblings
。
希望这会对你有所帮助。