find()方法在我的普通javascript项目中不起作用



我一直在做一个普通的javascript项目。

在控制台上,此行const tempPage = sublinks.find(({ page }) => page === text);作为undefined登录。


const sublinks = [
{
page: 'products',
links: [
{ label: 'payment', icon: 'fas fa-credit-card', url: 'products.html' },
{ label: 'terminal', icon: 'fas fa-credit-card', url: 'products.html' },
{ label: 'connect', icon: 'fas fa-credit-card', url: 'products.html' },
],
},
{
page: 'developers',
links: [
{ label: 'plugins', icon: 'fas fa-book', url: 'products.html' },
{ label: 'libraries', icon: 'fas fa-book', url: 'products.html' },
{ label: 'plugins', icon: 'fas fa-book', url: 'products.html' },
{ label: 'billing', icon: 'fas fa-book', url: 'products.html' },
],
},
{
page: 'company',
links: [
{ label: 'about', icon: 'fas fa-briefcase', url: 'products.html' },
{ label: 'customers', icon: 'fas fa-briefcase', url: 'products.html' },
],
},
];
const submenu = document.querySelector('.submenu');
const linkBtns = [...document.querySelectorAll('.link-btn')];
linkBtns.forEach((btn) => {
btn.addEventListener('mouseover', e => {
const text = e.currentTarget.textContent;
const tempBtn = e.currentTarget.getBoundingClientRect();
const center = (tempBtn.left + tempBtn.right) / 2;
const bottom = tempBtn.bottom - 3;
// ***********this line**************************
const tempPage = sublinks.find(({ page }) => page === text);
// ******************************************************
console.log(tempPage);

submenu.classList.add('show');
submenu.style.left = `${center}px`;
submenu.style.top = `${bottom}px`;
})
});

这是HTML代码。

<ul class="nav-links">
<li>
<button class="link-btn">Products</button>
</li>
<li>
<button class="link-btn">Developers</button>
</li>
<li>
<button class="link-btn">Company</button>
</li>
</ul>
<aside class="submenu">
hello there
</aside>

在HTML中:

<button class="link-btn">Products</button>

因此,在您的Javascript代码中:

const tempPage = sublinks.find(({ page }) => page === text)

"页面";将是";产品";,以及";文本";将是";"产品";

您可以将其更改为

const tempPage = sublinks.find(({ page }) => page === text.toLowerCase())

您应该将文本转换为小写page === text.toLowerCase(),因为按钮的所有文本节点都是大写的,因此在find()方法的每次迭代中都会返回false

最新更新