调用<p>标签内的值变化函数

时间:2016-05-26 05:19:05

标签: javascript html

在JavaScript中有什么方法可以在更改段落标记的值时调用函数。

概述:

HTML:

<p id="timer">00:00</p>
<button onclick="change()">My Button</button>

JS:

function change() {
  document.getElementById("timer").innerHTML = "00:01";
}

function hello() {
  alert("Hello");
}

当段落的值发生变化时,我想提醒(“你好”)。 像连续函数检查段落值的变化。

4 个答案:

答案 0 :(得分:11)

您可以MutationObserver使用characterData选项设置为true

&#13;
&#13;
<script>
  function change() {
    document.getElementById("timer").innerHTML = "00:01";
  }

  function hello() {
    alert("Hello");
  }
  window.onload = function() {

    var target = document.querySelector("p");

    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        hello()
      });
    });

    var config = {
      childList: true,
      subtree: true,
      characterData: true
    };

    observer.observe(target, config);
  }
</script>

<p id="timer">00:00</p>
<button onclick="change()">My Button</button>
&#13;
&#13;
&#13;

答案 1 :(得分:4)

试试这个MutationObserver API,(同时检查simple example

event.preventDefault()

<强>样本

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        //value changed, call the other API
        hello();
    });    
});
var observerConfig = {
    characterData: true //since only the node-value needs to be checked in your case
}; 
var targetNode = document.getElementById("timer");
observer.observe(targetNode, observerConfig);
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    //value changed, call the other API
    if ( mutation.type="childList" )
    {
       hello();
       //observer.disconnect();
    }
  });
});
var observerConfig = {
	childList: true
};
var targetNode = document.body;
observer.observe(targetNode, observerConfig);


document.getElementById("timer").innerHTML = "0.2";

window.hello = function (){
  alert(1);
}

答案 2 :(得分:1)

另外一个选择

function change() {
  document.getElementById("timer").innerHTML = new Date().getTime();
}

var prevValue = document.getElementById("timer").innerHTML;

setInterval(function() {

  currValue = document.getElementById("timer").innerHTML;

  if (prevValue != currValue) {
    prevValue = currValue;
    hello();

  }

}, 1);

function hello() {
  alert("Hello");
}
<p id="timer">00:00</p>
<button onclick="change()">My Button</button>

答案 3 :(得分:-1)

尝试使用onchange属性,或者这个可以帮助你:

Add event handler to HTML element using javascript