页面如下所示:
<html>
<span id="somespan">1000</span>
</html>
somespan 的值每 1 或 2 分钟增加一次。
使用 Javascript/JQuery,如何检查该值是否相同或每 5 分钟增加一次。
我的意思是,在 16:00 时,该值为 1000,2 分钟后,因此在 16:02 时,值为 1200。
我如何检查它是否已更改。
我想做一些类似的东西:
var somespan = $("#somespan").text();
if(somespan isnt changed) {
#console.log('still same.')
}
我将使用此代码的平台是 Google Chrome -> Tampermonkey
最佳答案
您可以实现 MutationObserver ,但这也可以。
var current_value = null;
setInterval( function() {
if (current_value != null) {
if (current_value != $('#somespan').text()) {
console.log('Value has changed!');
}
}
current_value = $('#somespan').text();
}, 1000 );
// For testing only
$('input').on('input', function() {
$('#somespan').text( $(this).val() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="somespan">1000</span>
<!-- For testing only -->
<br/>
<input type="text" value="1000">
通过 MutationObserver(无需轮询)
const observer = new MutationObserver(function(mutations) {
for (const mutation of mutations) {
if (mutation.type === 'childList') {
console.log('Value has changed!')
}
}
});
observer.observe(document.querySelector('#somespan'), {childList: true});
// For testing only
document.querySelector('input').addEventListener('input', function() {
document.querySelector('#somespan').innerHTML = this.value;
});
<span id="somespan">1000</span>
<!-- For testing only -->
<br/>
<input type="text" value="1000">
关于javascript - 如何检查 <span> 标记之间的值是否未更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51351802/