我正在尝试为用户输入关键字的网页制作搜索框,我的代码在所有元素的 href 中搜索该关键字,并隐藏所有那些在其 href 中不包含该关键字的元素。
我尝试了一个 JavaScript 代码,它读取 href 中的文本并读取搜索框中的文本,然后检查搜索框中的文本是否是 href 中字符串的子字符串。我已经使用 java Script 的 indexOf 函数来检查子字符串
此代码应显示那些在其 href 中包含关键字的元素,并隐藏那些在其 href 中不包含此关键字的元素。相反,什么都没有发生。
function MyFunction() {
var container, value, txtvalue, i, searchtxt, get;
get = document.getElementById("searchtext");
searchtxt = get.value.toUpperCase();
container = document.getElementById("back");
value = container.getElementByTagName("a");
for (i = 0; i < value.length; i++) {
txtvalue = value[i].href;
if (txtvalue.toUpperCase.indexOf(searchtxt) > -1) {
value.style.display = "";
} else {
a.style.display = "none"
}
}
}
.back {
width: 100%;
height: 625px;
}
.linkbox {
width: 11%;
height: 34%;
background-color: green;
top: 4%;
display: inline-block;
border: 1px solid black;
margin-left: 2.5%;
margin-top: 4%;
left: 3.5%;
box-shadow: 0px 20px 10px -8px black;
border-radius: 12px;
}
.text {
width: 100%;
top: 50%;
position: relative;
text-align: center;
font-size: 100%;
overflow: hidden;
}
<body style="margin:0; background-color:yellow;">
<input type="text" id="searchtext" placeholder="search here" />
<button class="toclick" onclick="MyFunction()"></button>
<div class="back" id="back">
<a href="1-spiderman-far-from-home.html">
<div class="linkbox" style="background:url('images0.jpg'); background-size:100% 100%;">
<div class="text"></div>
</div>
</a>
<a href="2-Aladdin-2019.html">
<div class="linkbox" style="background:url('images1.jpg'); background-size: 100% 100%;">
<div class="text"></div>
</div>
</a>
<a href="3-venom-2018.html">
<div class="linkbox" style="background:url('images2.jpg'); background-size:100% 100%;">
<div class="text"></div>
</div>
</a>
<a href="4-Alita-battle-angel-2019.html">
<div class="linkbox" style="background:url('images3.jpg'); background-size:100% 100%;">
<div class="text"></div>
</div>
</a>
<a href="5-Antman-and-the-wasp.html">
<div class="linkbox" style="background:url('images4.jpg'); background-size:100% 100%;">
<div class="text"></div>
</div>
</a>
<a href="6-Fantastic-beasts-crime-of-grindelwald-2019.html">
<div class="linkbox" style="background:url('images5.jpg'); background-size:100% 100%;">
<div class="text"></div>
</div>
</a>