gpt4 book ai didi

javascript - 简单的搜索栏,显示

转载 作者:行者123 更新时间:2023-12-05 05:11:50 24 4
gpt4 key购买 nike

好的,我已经找了一段时间了,但我还没有找到解决方案,所以我希望这不是一个愚蠢的问题......

我做了一个非常简单的网站,用来展示随机食谱,当你不知道晚餐做什么时,我希望也能搜索食谱,如果你知道你想要什么,或者只是检查拼写错误或其他...

菜谱只是

中的文本,我是这样制作的

<div id="1" class="recipe">
<h2>name</h2>
<h3>stuff I need</h3>
<ul>
<li>stuff</li>
</ul>
<h3>how to</h3>
<p>how to text</p>
<h1>time</h1>
</div>

然后我用这个css来隐藏它

.recipe{
display:none;
}

然后我制作了一个随机显示它们的按钮(到目前为止我有 15 个食谱)

function RandomDiv() {
var myarray= new Array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15");
var ChosenDiv = myarray[Math.floor(Math.random() * myarray.length)];

document.getElementById(ChosenDiv).style.display="inline-block";
</scipt>

我不知道是否有更简单的方法来做同样的事情,但到目前为止它是有效的现在我想在 中有一个搜索栏,我可以在其中写下名称,当我按下提交时,它会像按钮一样显示

我希望这有任何意义,如果有什么我忘记了,对不起,请告诉我我做错了什么

最佳答案

Nep,我准备了一个工作示例。如果有进一步的问题,请不要犹豫。

我已将您的代码分组到函数中,注释掉随机方法并添加带有输入的导航以搜索食谱。

function getReceipes() {
return document.getElementsByClassName('recipe');
}

function randomDiv() {
var receipes = getReceipes();

return receipes[Math.floor(Math.random() * receipes.length)];
}

// randomDiv().style.display="inline-block";

document.getElementById('search').addEventListener('keyup', function(e) {
var searchText = this.value;

Array.from(getReceipes()).forEach(function(recipe) {
if (searchText.length === 0) {
recipe.style.display = 'none';
} else {
var nameElement = recipe.getElementsByTagName('h2')[0];

if (nameElement && nameElement.innerText.indexOf(searchText) > -1) {
recipe.style.display = 'inline-block';
} else {
recipe.style.display = 'none';
}
}
});
});
.recipe {
display:none;
}
<nav>
<input id="search" type="text" placeholder="Type a name of recipe" />
</nav>
<main>
<div id="1" class="recipe">
<h2>first</h2>
<h3>stuff I need</h3>
<ul>
<li>stuff</li>
</ul>
<h3>how to</h3>
<p>how to text</p>
<h1>time</h1>
</div>
<div id="2" class="recipe">
<h2>second</h2>
<h3>stuff I need</h3>
<ul>
<li>stuff</li>
</ul>
<h3>how to</h3>
<p>how to text</p>
<h1>time</h1>
</div>
</main>

关于javascript - 简单的搜索栏,显示 <div>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55045900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com