简体   繁体   English

HTML 元素上的 Javascript onclick 事件

[英]Javascript onclick event on HTML element

I have got the code which allows me to search through a list of products and then generate an HTML list of those matching the search term.我得到了允许我搜索产品列表的代码,然后生成与搜索词匹配的产品的 HTML 列表。 My next step is to be able to click either on the accompanying picture of the product or its name and then add this into the shopping cart section.我的下一步是能够单击产品的随附图片或其名称,然后将其添加到购物车部分。 I understand an onclick event would assist in doing this but am not sure of the implementation.我了解 onclick 事件将有助于执行此操作,但不确定实施。 Any guidance would be greatly appreciated!任何指导将不胜感激!

Addition: I tried the code补充:我试过代码

HTML HTML

<img class="imgInteract">

JS JS

var imgInteract = document.getElementsByClassName('img')

to try and be able to select the img elements that are generated in the list but it didn't seem to work.尝试并能够 select 列表中生成的 img 元素,但它似乎不起作用。

HTML HTML

<form>
  <p>Please insert the items</p>
  <input type="text" id="box" />
</form>

<div id="root"></div>

<h3>
shopping cart
</h3>

CSS CSS

  img {
    height: 100px;
  }
  li {
    display: inline-block;
  }

JS JS

const catalog = {

  GalaxyTablet: {
    name: "GalaxyTablet",
    key: "galaxytablet",
    keywords: ["galaxy", "tablet", "samsung"],
    price: 800,
    image: "https://www.jbhifi.co.nz/FileLibrary/ProductResources/Images/150044-M-HI.jpg"
  },
  GalaxyPhone: {
    name: "GalaxyPhone",
    key: "galaxyphone",
    keywords: ["galaxy", "phone", "samsung"],
    price: 1000,
    image: "https://assets.kogan.com/files/product/etail/Samsung-/S10WHT_03.jpg?auto=webp&canvas=753%2C502&fit=bounds&height=502&quality=75&width=753"
  },
  HTCPhone: {
    name: "HTCPhone",
    key: "htcphone",
    keywords: ["htc", "phone"],
    price: 650,
    image: "https://cdn.mos.cms.futurecdn.net/ca063713e185be46e62ec2eb3762a540.jpg"
},

};

const form = document.querySelector("form");

form.addEventListener("submit", submitHandler);

function submitHandler(event) {
  event.preventDefault();

  const searchTerm = form.box.value;
  const results = search(searchTerm);

  render(results);
}

function search(searchTerm) {
  return Object.keys(catalog)
    .filter((key) => catalog[key].keywords.includes(searchTerm.toLowerCase()))
    .map((key) => catalog[key]);
}

function render(results) {
  const root = document.querySelector("#root");
  const list = results.map(itemToLi).join("");

  root.innerHTML = `<ul>
    ${list}
  </ul>`;
}

function itemToLi(item) {
  return `<li>${item.name}</li>$ ${item.price}<li> <li><img src="${item.image}"></li>`;
}

What you'd like to do here is this:你想在这里做的是:

function render(results) {
 ...

  root.innerHTML = `<ul>
     ${list}
  </ul>`;

  attachOnclickHandlerToEachImage();
}

function attachOnclickHandlerToEachImage(){
  var imgInteract = document.getElementsByTagName('img')

  for (let img of imgInteract) {
    img.addEventListener('click', addToCart.bind(this));
  }

}

function addToCart(img){
   console.log(img + "added to cart");
}

I think you should change your render method for the product list so both the image and product name are under the same <li> tag.我认为您应该更改产品列表的渲染方法,以便图像和产品名称都在同一个<li>标记下。

So your item to li looks like:所以你的项目 li 看起来像:

function itemToLi(item) {
  return `<li data-productkey="${item.key}">${item.name}$ ${
    item.price
  }<img src="${item.image}"></li>`;
}

Then in your render function.然后在您的渲染中 function。 You add a event listener to the li instead, so it will track the event when you click either on the image or on the product name.相反,您将事件侦听器添加到 li,因此当您单击图像或产品名称时,它将跟踪事件。

function render(results) {
  const root = document.querySelector("#root");
  const list = results.map(itemToLi).join("");

  root.innerHTML = `<ul>
    ${list}
  </ul>`;

  const products = document.querySelectorAll("li");
  products.forEach(product => {
    product.addEventListener("click", e => {
      console.log("added ", product.dataset.productkey);
    });
  });
}

You can use the data attribute to store the key of your product.您可以使用data 属性来存储产品的密钥。 So you know exactly which one was clicked.所以你确切地知道点击了哪一个。

You can see the Working demo here .您可以在此处查看工作演示

Add a class to your images and then use the event to add them to shoppin cart将 class 添加到您的图像,然后使用该事件将它们添加到购物车

function itemToLi(item) {
  return `<li>${item.name}</li>$ ${item.price}<li> <li><img  class="imgInteract" src="${item.image}"></li>`;
}

root.addEventListener('click',(e)=>{
    if(e.target.className=='imgInteract')
 console.log('add to shopping cart',e.target.src)
})

or you can add the class to the li and then retrieve the item you want to add或者您可以将 class 添加到li然后检索您要添加的项目

function itemToLi(item) {
  return `<li class="select">${item.name}</li>$ ${item.price}<li> <li><img  class="imgInteract" src="${item.image}"></li>`;
}

root.addEventListener('click',(e)=>{
    if(e.target.className=='select')

     console.log('add to shopping cart',e.target.textContent)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM