如何检测DOM元素的class属性何时发生变化

How to detect when the class attribute of DOM elements changes?

本文关键字:class 属性 何时发 变化 元素 DOM 何检测 检测      更新时间:2023-09-26

这需要一点解释。我用的是jquery播放列表,JWplayer,它的作用是读取播放列表。xml文件,生成滚动菜单,如下所示

<div class="jw_playlist_playlist">
   <div class="jw_playlist_item even">
      <div class="jw_playlist_title">Title</div>
      <div class="jw_playlist_description"></div>
   </div>
   <div class="jw_playlist_item odd">
      <div class="jw_playlist_title">Title2</div>
      <div class="jw_playlist_description"></div>
   </div>
</div>

,当一个项目被选中时,它将变为<div class="jw_playlist_item even playing"><div class="jw_playlist_item odd">。是否有一种方法,我可以检测这种变化与javascript,并提取标题?

我想你可以在JavaScript中创建一个计时器,每隔X秒检查一下元素是否存在。

<script> 
var title = ""; 
$(function() { // wait till page is loaded
    // sets a timer to repeat the function every 1 second
    setInterval(function() { 
        // if .play class div exists, take the title of the song
        if ($(".play").length > 0) { 
            title = $(".play jw_playlist_title").html();
            updateData();
        } else { 
        // otherwise set the title to be empty
            title = ""; 
        } 
     }, 1000); 
});
function updateData() {
    $("#demo").html("Current Song: "+title);
}

 </script> 
 <p id="demo">My First Paragraph</p>