上代码
( function($){
    
    $.fn.audio = function(musicURI){
        
            $(this).append(" <i class='fa fa-play'></i>");
            $(this).click(function(){
            
            if( element(musicURI)) {
                
                $(this).children('.fa').removeClass("fa-play");
                $(this).children('.fa').addClass("fa-pause");
            } else {
                $(this).children('.fa').removeClass("fa-pause");
                $(this).children('.fa').addClass("fa-play");
            }
            
        });
            
        debug('Audio');    
    };
    
    function debug(obj) {
        if(window.console && window.console.log) {
            
            window.console.log("%c jQuery Plugin " + obj, 'background-image:url(http://cc-cdn.b0.upaiyun.com/static/console.jpg); line-height: 10px; background-repeat: no-repeat; padding-left: 40px; background-position: left center; color: #F217B9; ');
        }
    };
    
    function element(uri) {
        
        
        
        if(! $("audio").length > 0)
        {
            var element = document.createElement("audio");
            element.setAttribute('src', uri);
            element.setAttribute('preload',true);
            element.setAttribute('loop',true);
            element.setAttribute('volume', 0.1);
        }
        //element.play();
        if(element.paused) 
        {
            element.play();
            return true;
        }
        else
        {
            element.pause();
            return false;
        }
    };
    
})(jQuery);
$("#audio").audio("http://m1.music.126.net/_-Or3YYe0bjwEXkiz-pWHw==/7733964790811266.mp3");
多次点击会有多个声音出来, 怎么避免
audio重复创建? 谢谢
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
首先的问题是并没有添加audio元素,你只是创建了audio而没有添加到页面中,你只要审查一下元素就能发现这个问题,你需要这样:
其二:
.length返回的是匹配元素的个数,因此没有元素时为0,那么! $("audio").length是true,true > 0为 true,于是就一直创建元素了。就这些,不过运行的话还有error。