我目前对 Javascript 整体还很陌生。所以我遇到了一些问题。有人告诉我,这段代码(在下面找到)有额外的变量,这些变量不是代码工作所必需的。它只是一个简单的文本查找器(您输入一些输入文本,添加搜索提示,它会根据要求突出显示搜索词。)我很困惑,我希望得到一些帮助。 (附注:不要以我的代码格式来评判我。我正在尽我最大的努力,哈哈)
代码在这里:
<html>
<head>
<title>Word Finder</title>
</head>
<body style="background: red; font-size: 1.5em; color: white; text-align: center">
<h1 style="font-size: 3em; color: white">Paste some text</h1>
<label for="entry text">Enter some text : </label>
<input type="text" id="entry text">
<button type="submit" onclick="loadText()" value="submit">Submit</button><br><br>
<label for="search text">Enter some words : </label>
<input type="text" id="search text">
<button type="submit" onclick="returnText()" value="submit">Submit</button><br><br>
<h1 style="font-size: 2em"> Result: </h1>
<p id="skull" style="font-size: 2em;"></p>
<h2 id="noir"></h2>
<p id="crow" style="color: white; border: 15px groove black;"></p>
<script>
var x;
var y;
function loadText() {
x = document.getElementById("entry text").value;
}
function returnText() {
y = document.getElementById("search text").value;
var tally = 0;
var l = x.length;
var newIndex = 0;
var locations = [];
var s = x.indexOf(y);
while (s < l - y.length + 1 && s > -1) {
locations.push(x.indexOf(y, s));
s = x.indexOf(y,s + 1);
tally++;
}
x = x.replaceAll(y, "<mark>" + y + "</mark>");
document.getElementById("crow").innerHTML = x;
document.getElementById("skull").innerHTML = "There are " + tally + " instances of " + "<mark>" + y + "</mark>" + " in the given text, they are " + "<mark>" + " highlighted " + "</mark>" + " below: ";
document.getElementById("noir").innerHTML = "There's a whole bunch of characters in your text! (" + l + " to be exact). ";
}
</script>
</body>
</html>
我确实尝试过自己检查每个变量,但每次我更改某些内容时,整个代码都会崩溃。我假设我遗漏了一些东西,但我不能确定。