JavaScript中有什么办法可以在段落标签的值更改时调用函数.
概述:
HTML:
@H_403_6@<p id="timer">00:00</p> <button onclick="change()">My Button</button>JS:
@H_403_6@function change() { document.getElementById("timer").innerHTML = "00:01"; } function hello() { alert("Hello"); }当段落的值更改时,我想提醒(“Hello”).
像一个连续的功能,检查段落的值的变化.
解决方法
您可以使用MutationObserver将characterData选项设置为true
@H_403_6@<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>