我正在尝试在我的网站上创建一个搜索表单,但我不确定如何比较字符串或者我的编码是否正确。 当用户在搜索栏中键入 div 的 ID 时,我希望我的 div 消失,但是当我尝试比较字符串时,没有任何反应。
这是我的代码:
<body>
<h1 class="title">News Journal</h1>
<h6 class="motto">What's better than having multiple sources ?</h6>
<input type="text" class="search" placeholder="Search for a website..." id="search">
<div id="news-container">
<p class="mostViewed">Most visited news websites...</p>
<div class="container">
<div class="divCNN" id="cnn">
<a target="_blank" href="https://www.cnn.com/"><img src="https://pmcdeadline2.files.wordpress.com/2016/11/cnn-logo-2.jpg?w=892&h=598&crop=1" class="CNN"></a>
<p class="description">CNN was founded in 1980 by American media proprietor Ted Turner as a 24-hour cable news channel. It was the first all-news television channel in the United States and CNN website has an average of 112 millions unique monthly visitors.<a target="_blank" href="https://www.cnn.com/"> Visit !</a></p>
</div>
</div>
</div>
</body>
我的Javascript:
function Search() {
var string = +document.getElementById("search").value;
if (string == "cnn") {
document.getElementById("cnn").style.display = 'none';
}
else {
document.getElementById("cnn").style.display = 'inline-block';
}
}
document.addEventListener("keyup", Search);
</script>
最佳答案
前面的 +
将尝试将值转换为数字。如果该值不可转换为数字,则返回 NaN
,最终不满足条件:
更改 var string = +document.getElementById("search").value;
到
var string = document.getElementById("search").value;
function Search() {
var string = document.getElementById("search").value;
if (string == "cnn") {
document.getElementById("cnn").style.display = 'none';
}
else {
document.getElementById("cnn").style.display = 'inline-block';
}
}
document.addEventListener("keyup", Search);
<h1 class="title">News Journal</h1>
<h6 class="motto">What's better than having multiple sources ?</h6>
<input type="text" class="search" placeholder="Search for a website..." id="search">
<div id="news-container">
<p class="mostViewed">Most visited news websites...</p>
<div class="container">
<div class="divCNN" id="cnn">
<a target="_blank" href="https://www.cnn.com/"><img src="https://pmcdeadline2.files.wordpress.com/2016/11/cnn-logo-2.jpg?w=892&h=598&crop=1" class="CNN"></a>
<p class="description">CNN was founded in 1980 by American media proprietor Ted Turner as a 24-hour cable news channel. It was the first all-news television channel in the United States and CNN website has an average of 112 millions unique monthly visitors.<a target="_blank" href="https://www.cnn.com/"> Visit !</a></p>
</div>
</div>
</div>
关于javascript - 搜索后隐藏/显示 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50539637/