【问题标题】:How to execute function when element changes? (Without setInterval)元素变化时如何执行函数? (没有 setInterval)
【发布时间】:2018-06-23 20:06:21
【问题描述】:

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

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

对报告进行投票后,网页将删除所有当前报告内容并通过 Jquery 从另一个报告中加载所有数据。在加载报表时(或未加载报表时),它会将 #reportInfo 的所有子 div 值设置为“--”,并从 #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 的文本发生变化时执行,而不是在设定的时间间隔之后执行。有什么办法可以做到吗?

【问题讨论】:

  • $('.reportReason').on('change', function(){console.log($(this).text()})
  • $('.reportReason')是什么类型,是input,是divspan - 使用<>按钮构建一个小例子
  • 查看这里了解更多详情 - api.jquery.com/on
  • @Pilan 这是一个 div 元素。
  • @DanielKrom 这只会导致它重复执行该功能并停止网页。我正在寻找每次.reportReason 的文本更改后只执行一次开关功能的东西。

标签: javascript jquery


【解决方案1】:

多多 :)

$( '#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/>

【讨论】:

  • 我一定会在回家后立即测试一下。
  • 回家吧——现在! :D
  • @LordNazo 当然,看看selectors - 例如span.bla all spans with class bla
  • 看看这个jsfiddle.net/teqc48nd@Pilan 在我看来是对的
  • @Emeeus 更新了你的小提琴(缺少 jQuery)-updated Fiddle
【解决方案2】:

MutationObserver API

如果.reportReason 是一个表单控件,例如输入、文本区域、复选框等,那么在事件中访问其数据要比使用跨度容易得多。表单控件具有专门的事件,例如处理文本的 changeinput,但话又说回来,这将取决于可能不适用于您的情况的用户交互(至少以直接方式)。

假设文本本身来自您几乎无法控制或无法控制的来源,我们将从span.reportReason 开始并确定文本何时插入其中。我建议您将来跟踪查找文本本身来源所需的步骤。我确定这是XY Problem

为了监控span.reportReason 上发生的变化,我们可以使用MutationObserver API。在下面的演示中,创建了一个观察者来检测span.reportReason 内容的任何变化。它将在添加或删除文本时记录更改。 注意:所有带有console.log(...) 语句的行都是您应该调用函数的地方。我并不想尝试在 switch() 中找到这些函数,因此将它们替换为 console.log,这足以证明代码正常运行。

演示

部分代码标记为:“TEST NOT REQUIRED”,这意味着它仅用于演示目的,解决方案本身不需要它。

var tgt = document.querySelector('.reportReason');
var cfg = {
  attributes: false,
  childList: true,
  characterData: true
};

var monitor = new MutationObserver(function(changes) {
  changes.forEach(function(change) {
    console.log();
    for (let i = 0; i < change.addedNodes.length; i++) {
      console.log(`MUTATION TYPE: ${change.type} | "${change.addedNodes[i].textContent}" added`);
    }

    for (let i = 0; i < change.removedNodes.length; i++) {
      console.log(`MUTATION TYPE: ${change.type} | "${change.removedNodes[i].textContent}" removed`);
    }
  });
});


monitor.observe(tgt, cfg);

function reportReason(e) {

  const flag = $('.reportReason').text();

  switch (flag) {
    case "Inappropriate Username":
      console.log(`‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
REASON: Username sux.`);
      break;
    case "Spamming":
      console.log(`‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
REASON: User is spamming scum.`);
      break;
    case "Account not validated":
      console.log(`‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
REASON: User has not validated account yet.`);
      break;
    case "Multiple accounts":
      console.log(`‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
REASON: User has multiple accounts, delete all but the newest account.`);
      break;
    default:
      console.log(`‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
REASON: Specific Flag: ${flag}`);
      break;
  }
}



// ?TEST NOT REQUIRED?

$('button').on('click', function() {
  let flag = $('#test').val();
  $('.reportReason').text(flag);
  reportReason();
});

// ?TEST NOT REQUIRED?
.as-console-row:after {
  display: none !important
}

select,
button {
  font: inherit
}
<!--?TEST NOT REQUIRED?-->
<fieldset class='set'>
  <legend>Test</legend>
  <select id='test'>
    <option></option>
    <option>Inappropriate Username</option>
    <option>Spamming</option>
    <option>Account not validated</option>
    <option>Multiple accounts</option>
    <option>Other Reason...</option>
  </select>
  <button type='button'>TEST</button>
</fieldset>
<!--?TEST NOT REQUIRED?-->

<div>
  <span class="rititle">Reported Reason:</span>
  <span class="rivalue">
    <span class="reportReason"></span>
  </span>
</div>




<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

    猜你喜欢
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多