繁体   English   中英

内部值改变时调用函数 <p> 标签

[英]call function on change of value inside <p> tag

在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");
}

当段落的值更改时,我想提醒(“ Hello”)。 类似于连续函数的功能,用于检查段落值的变化。

您可以将MutationObservercharacterData选项设置为true

 <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> 

尝试使用此MutationObserver API(也请查看此简单示例

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); } 
 <p id="timer">0.0</p> 

另一种选择

 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> 

尝试使用onchange属性,也许这可以帮助您:

使用JavaScript将事件处理程序添加到HTML元素

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM