jQuery切换类

前端之家收集整理的这篇文章主要介绍了jQuery切换类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在将jQuery的toggleClass函数添加到我的其余代码中时遇到了麻烦.该页面上有几个 HTML5音频标签,通过jQuery控制.我试图将切换功能添加到我的jQuery音频控制功能,但它没有添加类,随后音频控件不起作用..所以我想这是一些奇怪的语法错误.

你们推荐什么?下面是一个jsFiddle和我(不幸的)弱尝试:)

http://jsfiddle.net/danielredwood/FTfSq/10/

HTML:

<div id="music_right">
    <div class="thumbnail" id="paparazzi">
        <a class="playback">
            <img class="play" src="http://www.lucisz.com/imgs/play.png" />
        </a>
        <audio>
         <source src="../audio/fernando_garibay_paparazzisnlmix.ogg" type="audio/ogg" />
            <source src="../audio/fernando_garibay_paparazzisnlmix.mp3" type="audio/mpeg" />
            Your browser does not support HTML5 audio.
        </audio>
    </div>
    <div class="thumbnail" id="danceinthedark">
        <a class="playback">
            <img class="play" src="http://www.lucisz.com/imgs/play.png" />
        </a>
        <audio>
         <source src="../audio/fernando_garibay_danceinthedark.ogg" type="audio/ogg" />
            <source src="../audio/fernando_garibay_danceinthedark.mp3" type="audio/mpeg" />
            Your browser does not support HTML5 audio.
        </audio>
    </div>
    <div class="thumbnail" id="bornthisway">
        <a class="playback">
            <img class="play" src="http://www.lucisz.com/imgs/play.png" />
        </a>
        <audio>
         <source src="../audio/fernando_garibay_bornthisway.ogg" type="audio/ogg" />
            <source src="../audio/fernando_garibay_bornthisway.mp3" type="audio/mpeg" />
            Your browser does not support HTML5 audio.
        </audio>
    </div>
</div>

JavaScript的:

var curPlaying;
$(function() {
    $(".playback").click(function(e){
        e.preventDefault();
        var song = $(this).next('audio')[0];
        song.toggleClass("playing");
        if(song.paused){
            song.play();
            if(curPlaying) $("audio","#"+curPlaying)[0].pause();
        } else {
            song.pause();
            }
        curPlaying = $(this).parent()[0].id;
    });
});

//the function below works,but doesn't have the add/remove class functions

var curPlaying;
$(function() {
    $(".playback").click(function(e) {
        e.preventDefault();
        var song = $(this).next('audio')[0];
        if (song.paused) {
            song.play();
            if (curPlaying) $("audio","#" + curPlaying)[0].pause();
        } else {
            song.pause();
        }
        curPlaying = $(this).parent()[0].id;
    });
});

解决方法

我会使用 .addClass().removeClass(),因为它会清理你的代码并允许你使用CSS来执行所有布局工作:
$('thumbnail').toggle(function(){
    $('.play',this).removeClass('pausing');
    $('.play',this).addClass('playing');
},function(){
    $('.play',this).addClass('pausing');
    $('.play',this).removeClass('playing');
});

猜你在找的jQuery相关文章