我正在尝试在我的网站上搜索表单,而且我不确定如何比较字符串或我是否正确编码。 当用户在搜索栏中输入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>
答案 0 :(得分:2)
前面的+
会尝试将值转换为数字。如果该值不可转换为数字,则返回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);
&#13;
<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>
&#13;