问题
I have following page structure
<div class="main">
<article class="article">
<!-- ... -->
<div class="article-footer>
<ul>
<li><a href="#" class="article-play" data-play="3" data-src="http://..."></a></li>
<li>...</li>
<!-- ... -->
</ul>
</div>
</article>
<article class="article playing"> <!-- Notice Additional Class .playing
<!-- ... -->
<div class="article-footer>
<ul>
<li><a href="#" class="article-play" data-play="3" data-src="http://..."></a></li>
<li>...</li>
<!-- ... -->
</ul>
</div>
</article>
<!-- ... -->
</div>
So what I want to do is, inside this click function:
$(".audiojs .play-pause").click(function() {
<!-- Code Here -->
})
on click replace data attribute inside anchor tag with class .article-play
that is inside article with class .playing
from data-play="3"
to data-pause="4"
, However in a way that it checks that if there is data-play="3"
than on click replace it with data-pause="4"
else if there is data-pause="4"
than replace it to data-play="3"
回答1:
$(".audiojs .play-pause").click(function() {
var element = $('.playing .article-play')
var play = element.attr('data-play')
var pause = element.attr('data-pause')
if(play == '3'){
element.removeAttr('data-play');
element.attr("data-pause",'3');
}else if(pause == '4'){
element.removeAttr('data-pause');
element.attr("data-play",'4');
}
});
回答2:
I believe the following should work (un-tested):
var dataPlay = $(".playing a.article-play").data("play");
var dataPause = $(".playing a.article-play").data("pause");
if (dataPlay == "3") {
$(".playing a.article-play").removeAttr("data-play").attr("data-pause", "4");
} else if (dataPause == "4") {
$(".playing a.article-play").removeAttr("data-pause").attr("data-play", "3");
}
回答3:
var a = $("article.playing a.article-play")
a.each(function(){
var playAttr = $(this).attr("data-play")
var pauseAttr = $(this).attr("data-pause")
if(playAttr){
if(playAttr == "4"){
$(this).removeAttr("data-play");
$(this).data("pause",3);
}
}
if(pauseAttr){
if(pauseAttr == "3"){
$(this).removeAttr("data-pause");
$(this).data("play",4);
}
}
});
回答4:
I think you can separate the method that handles pause
from the method that handles play
simplified HTML
<div class="playing">
<div id="output"></div>
<a href="#" class="article-play" data-play="4">click</a>
</div>
JS
$(".playing").on("click", ".article-play[data-pause]", function () {
$(this).removeAttr("data-pause");
$(this).attr("data-play", 4);
$("#output").text("playing 4");
});
$(".playing").on("click", ".article-play[data-play]", function () {
$(this).removeAttr("data-play");
$(this).attr("data-pause", 3);
$("#output").text("pausing 3");
});
jsFiddle
This answer is based on the answers I received to the question I asked while trying to implement this solution
来源:https://stackoverflow.com/questions/16942551/find-specific-anchor-tag-and-replace-data-atribute-on-click