gpt4 book ai didi

javascript - 在继续之前等待 DOM 元素中的特定文本

转载 作者:行者123 更新时间:2023-11-29 21:05:25 24 4
gpt4 key购买 nike

我有一个函数,它应该在返回值之前等待一些文本发生变化:

function getElementText() {
while(isLoading()) {
}
return $('#element').text();
}

function isLoading() {
return $('#element')[0] &&
$('#element').text().indexOf('Loading') >= 0;
}

但是我认为空的 while 不是一个好的选择(它会阻塞事件循环吗?)

最佳答案

无需 jQuery 或任何其他外部库,您只需使用 MutationObserver:https://developer.mozilla.org/en/docs/Web/API/MutationObserver

这是一个简单的例子,当你的文本发生变化时(在我的例子中是 5 秒后),你会收到类型为 characterData 的通知:

// select the target node
var target = document.getElementById('some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true, attributes: true, subtree: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
//observer.disconnect();
setTimeout(function() {
target.innerText = 'Changed text!';
}, 5000);
<div id="some-id">
AAA
</div>

从观察者的配置中删除所有不需要监视更改的属性

关于javascript - 在继续之前等待 DOM 元素中的特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44345731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com