2014-06-10 78 views
-4

无法使用addClass方法,也无法通过$(this)在动态加载的元素上保存DOM元素的实例。我已经使用.on方法来处理这些元素上的点击事件,但我无法操作它们。动态元素上的jQuery方法

$(document).on("click",".PlayPause",function(){ 
      if($(this).attr('src') == 'img/Play.png'){ 
       $(this).attr('src','img/Pause.png'); 
       var songId = $(this).parent().siblings('.Top_Container').children('input').val(); 
       $.post('songs.php',{songId : songId}, function(path){ 
        if(globalSong.playState && !($(this).hasClass('prevSelection'))){ 
         $('.prevSelection').attr('src','img/Play.png'); 
         globalSong.pause(); 
         $('.prevSelection').removeClass('prevSelection'); 
        } 
        globalSong = soundManager.createSound({ 
         id: ("sound" + songId), 
         url: (songsPath + path), 
         volume: userPrefVolume 
        }); 
        globalSong.play(); 
        $(this).addClass('prevSelection'); 
       }); 
      } else { 
       $(this).attr('src','img/Play.png'); 
       globalSong.pause(); 
      } 
     }); 
+6

里面哪里是代码..? –

回答

0

您需要的功能后保存$(this)()

$(document).on("click",".PlayPause",function(){ 

      var $this = $(this); //////Save this here////// 

      if($(this).attr('src') == 'img/Play.png'){ 
       $(this).attr('src','img/Pause.png'); 
       var songId = $(this).parent().siblings('.Top_Container').children('input').val(); 
       $.post('songs.php',{songId : songId}, function(path){ 
       //////////Use $this instead of $(this) inside here/////////// 
        if(globalSong.playState && !($(this).hasClass('prevSelection'))){//$this 
         $('.prevSelection').attr('src','img/Play.png'); 
         globalSong.pause(); 
         $('.prevSelection').removeClass('prevSelection'); 
        } 
        globalSong = soundManager.createSound({ 
         id: ("sound" + songId), 
         url: (songsPath + path), 
         volume: userPrefVolume 
        }); 
        globalSong.play(); 
        $(this).addClass('prevSelection'); //$this 
       }); 
      } else { 
       $(this).attr('src','img/Play.png'); 
       globalSong.pause(); 
      } 
     }); 

使用$this而不是$(this)$.post()功能