本文介绍了调用内部值变化的函数< p>标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
JavaScript中有什么方法可以在段标记的值发生更改时调用函数。
概述:
HTML:
< p id =timer> 00:00< / p>
< button onclick =change()>我的按钮< /按钮>
JS:
function change(){
document.getElementById(timer)。innerHTML =00:01;
函数hello(){
alert(Hello);
}
段落值改变时我想提醒(Hello) 。
类似于连续函数检查段落值的变化。
解决方案
您可以使用 MutationObserver
与 characterData
选项设置为 true
< script> function change(){document.getElementById(timer)。innerHTML =00:01; }函数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>
Is there any way in JavaScript by which I can call a function when the value of a paragraph tag is changed.
Overview:
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");
}
I want to alert("Hello") when the value of paragraph is changed.Something like a continuous function checking for a change in the value of paragraph.
解决方案
You can use MutationObserver
with characterData
option set to 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>
这篇关于调用内部值变化的函数< p>标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!