我试图让我的脚本只记录一次字符串。因此,当创建新字符串时,它只会记录新字符串...此脚本会立即记录所有字符串。我想找到一种方法,让它只记录 ID 为“team_log_actual”的元素中新创建的子元素的 .innerText
。
可以随时添加 child 。
这是我的脚本:
setInterval(function() {
var logelement = $('#team_log_actual');
var foo = document.getElementById('team_log_actual');
for (let i = 0; i < foo.children.length; i++) {
//console.log(foo.children[i].innerText);
var PRINTactions = foo.children[i].innerText;
var PRINTactionsEle = foo.children[i];
var fields = PRINTactions.split(/ /);
var Username = fields[2]; //grabs the second field from the splitted string. which is the username..
var text1 = fields[3];
var text2 = fields[4];
var text3 = fields[5];
var text4 = fields[6];
var text5 = fields[7];
var text6 = fields[8];
var text7 = fields[9];
var text8 = fields[10];
var text9 = fields[11];
var text10 = fields[12];
//Defined multiple just in case. Each field will contain a string. If one is there, but it's highly unlikely to go past 5-6.
var combinetext = fields[3] + " " + fields[4] + " " + fields[5] + " " + fields[6] + " " + fields[7];
if (combinetext.includes("used item") == true) {
console.log(Username + " : " + combinetext) // log the Username and the combinedtext. Only if the combinetext includes the string "in ejector".
}
}
}, 10000); // Run every 10 seconds.
最佳答案
使用 MutationObserver 解决。用户推荐:CodeWalker
// Solved code.
var Logconsole = document.getElementById('team_log_actual');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
for (var i = 0; i < mutation.addedNodes.length; i++) {
//This var gets the innertext of the new element.
var TextFromNewElement = mutation.addedNodes[i].innerText;
console.log(TextFromNewElement);
}
});
});
observer.observe(Logconsole, {
childList: true
});
//Test code. ----- Create a fake element every 5 seconds.
var testelement = document.createElement('div');
testelement.id = 'team_log_actual';
testelement.innerHTML = '<p> <b>[<span style="color: #0FF">USER:</span>] <bdi style="color: #0FF;">User2</bdi></b> harvest a plant.</p>'
setInterval(function(){
//every 5 seconds, add the test element.
Logconsole.appendChild(testelement)
}, 5000);
<div id="team_log_actual" class="log">
<p> <b>[<span style="color: #0FF">USER:</span>] <bdi style="color: #0FF;">User1</bdi></b> planted a seed.</p>
</div>
关于javascript - 记录创建的元素的内部文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58081333/