You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

搜索栏按元素ID搜索功能失效问题求助

搜索栏按元素ID搜索功能失效问题求助

我正在给我的搜索栏写逻辑,想通过元素ID来搜索页面里的内容,但怎么试都没效果。页面里的元素都是带图片的,所以用了现在这种方式展示元素。折腾好多次都没解决,麻烦各位帮忙看看问题出在哪!

我的HTML代码:

<html lang="en">

<head>

<title>BONIXS</title>

<link rel="shortcut icon" href="BONIXS.ico" type="image/x-icon">

<link rel="stylesheet" href="STEAM.CSS">

<script src="STEAM.js"></script>

</head>

<body>

<div>

<h1 id="Start">BONIXS</h1>

</div>

<br><br>

<input type="text" id="searchBar" placeholder="Search">

<ul id="searchResults"></ul>

<br><br><br><br>

<div>

<h2 id="Action">ACTION</h2>

</div>

<ul>

<a href="Action/Ghostrunner/Ghost Runner.html"><img src="Action/Ghostrunner/Ghostrunner.jpg" alt="Ghost Runner" class="Games" id="Ghostrunner"></a>

<a href="Action/Atomic Heart/Atomic Heart.html"><img src="Action/Atomic Heart/Atomic Heart.jpg" alt="Atomic Heart" class="Games" id="Atomic-Heart"></a>

<a href="Action/High On Life/High On Life.html"><img src="Action/High On Life/High On Life.jfif" alt="High On Life" class="Games" id="High-On-Life"></a>

</ul>

</body>

</html>

JavaScript逻辑代码:

const searchBar = document.getElementById('searchBar');

const searchResults = document.getElementById('searchResults');

searchBar.addEventListener('keyup', function(event) {

console.log('Keyup event detected'); // Check if event listener is triggered

if (event.key === 'Enter') {

const searchTerm = searchBar.value.toLowerCase();

console.log('Search term:', searchTerm); // Check the search term

searchResults.innerHTML = '';

const matchingResults = performSearch(searchTerm);

console.log('Matching results:', matchingResults); // Check the matching results

displayResults(matchingResults);

}

});

function performSearch(searchTerm) {

const allElements = document.querySelectorAll('[id]');

return Array.from(allElements).filter(element => element.id.toLowerCase().includes(searchTerm));

}

function displayResults(results) {

results.forEach(result => {

const li = document.createElement('li');

li.textContent = result.id;

searchResults.appendChild(li);

});

}

我已经反复测试了好几次,这个搜索功能就是不工作,虽然加了控制台日志排查,但还是没找到问题根源,有没有大佬能帮忙分析一下?

备注:内容来源于stack exchange,提问作者A-1500

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 12:48:01