首页 > 解决方案 > 带有 JavaScript 的按钮

问题描述

我是 JavaScript、html 和 CSS 方面的新手,我正在尝试制作一个关于公式 1 的简单网页。在此页面中,我尝试制作一个包含 10 个按钮的小菜单,每个按钮都会引导您进入公式一个团队网页。我第一次只使用 html 但后来意识到我可能可以使用 JavaScript 中的循环来完成它并节省大量的行和时间,我对如何做到这一点有一些想法,但我不知道如何执行想法正确。

首先,我将创建一个包含 10 个对象的列表,每个对象都有一个图像链接和 10 个团队之一的网页以在按钮中使用:

var teams = [
    {name: mercedes, logo: teammercedes.icon, web: mercedes.com
    {name: ferrari, logo: ferrari.icon, web: ferrari.com}

然后会创建一个“for”(我猜这里)

    for(i = 0; i < 11; i++){

    Now, I have no idea how to put this in JS but I here is what I want:

    mercedes is i = 0, so the JS create all the button tag structure using 
    the Mercedes logo I saved in the list above to decorate de button.

    then it goes to i = 1, which would be Ferrari, and the JS create again 
    all the button tag structure using the Ferrari logo saved in the list

}

我认为通过这种方法,我需要在 JS 中编写一次按钮结构,并以某种方式将其中的信息推送 10 次,使用列表上定义的 10 个不同索引

标签: javascripthtml

解决方案


你在正确的路线上。创建公司数组,然后遍历名称以构建一些 HTML,然后将其附加到菜单。使用一些 CSS 来设置按钮样式。

这个例子使用了一些现代的 JS 技术,我保证不会吓跑你。答案末尾有完整的文档,但我会尝试解释一下。

// The array of companies that you wanted
const companies = ['Mercedes', 'Renault', 'Saab', 'Fiat'];

// We cache the menu element using `querySelector`
const menu = document.querySelector('#menu');

// We assign a listener to the menu so when it is clicked
// we can redirect to a new page based on the the button id
menu.addEventListener('click', handleClick, false);

// For the buttons we can `map` over the array and create
// a new array of HTML that we `join` into a string at the end.
// I've used a dummy image here, but you can substitute in your
// own images for the img source
const buttons = companies.map(company => {
  const src = `https://dummyimage.com/100x30/b5d19d/000&text=${company}`;

  // Return some HTML that uses a class, a data attribute for
  // the company name, and the src image for the "button", and
  return `<img class="company" data-id="${company.toLowerCase()}" src="${src}" />`;

// then `join` the new array up into one string
}).join('');

// Add the button HTML to the menu element
menu.innerHTML = buttons;

// When the listener is called
function handleClick(e) {

  // Grab the id value from the data attribute, and
  // the className from the element that was clicked
  // using destructuring assignment
  const { dataset: { id }, className } = e.target;

  // Check to see if the element that was click was a button
  if (className === 'company') {

    // And then navigate to your new page
    console.log(`http://example.com/${id}.html`);
    // window.location.href = `http://example.com/${id}.html`;
  }
}
.company { border: 1px solid white; border-radius: 10px; display: block; margin: 1em; cursor: pointer; }
.company:hover { border: 1px solid black; }
<div id="menu"></div>

附加文件


推荐阅读