首页 > 解决方案 > 元素变化时如何执行函数?(没有 setInterval)

问题描述

我尝试将脚本配置为根据显示的报告类型(即 span 元素的文本.reportReason)自动单击页面上的某些按钮。

这是该页面的典型外观示例:http ://www.blankmediagames.com/Trial/viewReport.php?id=1409368 (我无法链接该页面以对报告进行投票,因为必须有过多的要求通过玩游戏来认识。)

在对报告进行投票后,网页将删除所有当前报告内容并通过 Jquery 从另一个报告中加载所有数据。在加载报告时(或未加载报告时),它将所有子 div 值设置#reportInfo为“--”,并从#reportContent.

这是我的脚本的代码:

    switch ($('.reportReason').text()) {
    case "Inappropriate Username":
        //This is an INAPPROPRIATE USERNAME report
        reportIU();
        break;
    case "Spamming":
        //This is a SPAMMING report
        reportSpamming();
        break;
    case "Leaving":
        //This is a LEAVING report
        reportLeaving();
        break;
    case "Multi-accounting":
        //This is a MULTI-ACCOUNTING report
        reportMulti();
        break;
    default:
        //Report hasn't loaded or report type is 'Other'
        break;
}

我想让 switch 语句在每次 span 元素的文本.reportReason发生变化时执行,而不是在设定的时间间隔之后执行。有什么办法可以做到这一点?

标签: javascriptjquery

解决方案


多达 :)

$( '#btn' ).click( function() {
  // simulate ajax change
  if( $( 'div#test' ).text() != "a" ) {
    $( 'div#test' ).text( "a" );
  }
} );

$('div#test').on('DOMNodeInserted',function() {
  console.log('div changed!');
  
  // do your switchy stuff
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Div:
<div id='test'>Some randome content.</div><br/>
<br/>
<input id='btn' type='button' value='Change div content'/>
<br/>


推荐阅读