【问题标题】:Trigger JavaScript event if div innerText change如果 div innerText 发生变化,则触发 JavaScript 事件
【发布时间】:2014-08-14 20:16:40
【问题描述】:

我想在 div 的 innerText 发生变化时发出警报:

myDiv.addEventListener("change", function() {
    if (myDiv.innerText != "some text")
        alert('innerText has changed.');
},false);

没有用,请帮忙。

【问题讨论】:

标签: javascript addeventlistener innertext


【解决方案1】:

试试

document.addEventListener("change", function()......

【讨论】:

    【解决方案2】:

    change 事件未指定在文本更改的任何时候触发。它仅在 textarea 失去焦点(用户点击或离开)时触发。所以你的事件只会在这种情况发生时触发。

    除了使用interval 不断检查文本区域的值之外,没有优雅的方法可以做到这一点(据我所知)。

    请注意 this fiddle 中的 change 事件仅在 textarea 失去焦点后触发。

    更多信息请参见this answer...

    【讨论】:

      【解决方案3】:

      代表 OP 发布

      我找到了解决办法:

      // THIRD FUNCTION (changes the text)
      var i = 0;
      function thirdFUN(){
          i++;
          var popo = document.getElementById('myDiv');
          popo.innerText = i;
      }
      setInterval(thirdFUN, 500);
      
      //---------------------------------------------------------------
      
      // JQUERY
      /*var popo = $('#myDiv');
      $('#myDiv').bind("DOMSubtreeModified",function(){
          if (popo.html() == "10")
          console.log('changed');
      });
      */
      
      //---------------------------------------------------------------
      
      // PURE JS
      window.onload = function(){
      
      var popo = document.querySelector('#myDiv');
      
      var observer = new MutationObserver(function(mutations){
          mutations.forEach(function(mutation){
              console.log(mutation.type); // <- It always detects changes
              if (popo.innerHTML == "10"){
                  alert('hello');
              }
          });    
      });
      
      var config = {characterData: true, subtree: true};
      observer.observe(popo, config);
      //observer.disconnect();
      
      }
      

      这是also a JS Fiddle

      【讨论】:

        【解决方案4】:

        myDiv.addEventListener("DOMCharacterDataModified", function (event) { // ... add your code he }, false);

        使用 DOMCharacterDataModified 检测 innerText 更改事件

        【讨论】:

          猜你喜欢
          • 2015-01-02
          • 2021-11-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-13
          • 2010-12-15
          • 1970-01-01
          • 2011-12-14
          相关资源
          最近更新 更多