var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var text = reader.result;
var output = document.getElementById('output');
const lines = text.split('\n');
lines.forEach((line) => {
const div = output.appendChild(document.createElement('div'));
const textSplitAroundAt = line.split('Microsoft');
textSplitAroundAt.forEach((text, i) => {
div.appendChild(document.createTextNode(text));
if (i === textSplitAroundAt.length - 1) return;
const span = div.appendChild(document.createElement('span'));
span.textContent = 'Microsoft';
span.className = 'colorMicrosoft';
});
});
document.getElementById('populateAt').textContent = text.split('@').length - 1;
document.getElementById('populateMicrosoft').textContent = text.split('Microsoft').length - 1;
document.getElementById('populateGoogle').textContent = text.split('Google').length - 1;
};
reader.readAsText(input.files[0]);
};
.colorMicrosoft
{
color: blue;
background-color: red;
}
.colorGoogle
{
color: red;
background-color: blue;
}
.colorAt
{
color: blue;
background-color: green;
}
<center>
<h1>.TXT Log Parser</h1>
</center>
<center>
<div>I would like the number of times '@' symbol appears here: <span id="populateAt"> ... </span></div>
<div>I would like the number of times 'Microsoft' symbol appears here: <span id="populateMicrosoft"> ... </span></div>
<div>I would like the number of times 'Google' symbol appears here: <span id="populateGoogle"> ... </span></div>
</center>
<center>
<h2><input type='file' accept='text/plain' onchange='openFile(event)'></h2>
</center>
<br/>
<div id='output'>...</div>
只要看看下面的代码片段,我正在将文本文件加载到div中。 目前,我可以计算出特定字符串出现的次数。 另外,我可以通过span更改每个“Microsoft”字符串的颜色。 但是,我似乎无法为“Google”和“@”添加多个跨度 我应该使用数组吗?若然,怎么做?