Javascript 如何在单击网格中的任何图像时运行函数?
所以,我有一个叫做产品的图像块,它位于“产品网格”中 每个组都有不同的值,尽管它们现在是静态输入的,但我想将来它们都会通过某种适配器添加。在这种情况下,只定义了类,没有定义ID 如何使图像在网格上的任何位置被单击时都能够检索:Javascript 如何在单击网格中的任何图像时运行函数?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,所以,我有一个叫做产品的图像块,它位于“产品网格”中 每个组都有不同的值,尽管它们现在是静态输入的,但我想将来它们都会通过某种适配器添加。在这种情况下,只定义了类,没有定义ID 如何使图像在网格上的任何位置被单击时都能够检索: 产品名称(产品名称) 产品价格(产品价格) 图像源(images/product7.jpg);然后发送到下一页 首先,我知道如果设置了一个id,您可以获得类似值的属性。当数据不在下面的单个标记/元素中时,javascript是如何编写的?此外,假设我没有定义id,如何仅从
这是一个块的外观,复制了几次:
<!-- Product -->
<div class="product">
<div class="product_image" value="Yellow"><img src="images/product_7.jpg" alt=""></div>
<div class="product_extra product_new"><a href="categories.html">New</a></div>
<div class="product_content">
<div class="product_title"><a href="product.html">Yellow Phone</a></div>
<div class="product_price">$670</div>
</div>
</div>
$670
都在一个
<div class="row">
<div class="col">
<div class="product_grid">
每个副本都定义了相同的类,只是在innerhtml值(如price)上有所不同。然后将这些值发送到另一个页面中进行处理。使用jquery,您可以执行以下操作:
var $productImages = $('.product_image > img');
$productImages.click(function(){
var $this = $(this);
var $product = $this.parents('.product');
var title = $product.find('.product_title > a').text();
var price = $product.find('.product_price').text();
var imgSource = $this.attr('src')
// all values are here, now you can do whatever you want with them
alert(`Title is ${title}, price is ${price} and image source is ${imgSource}`);
})
根据我所能理解的内容(使用jquery),我对以下内容进行了修改: 实际上这是很基本的。 jquery部分如下所示
$('.product_grid').on('click', 'img', function(){
var url = 'your-site.html';
var el = $(this).parents('.product');
var params = {
title: el.find('.product_title').text(),
price: el.find('.product_price').text(),
img_src: el.find('.product_image img').attr('src')
};
window.location.href = url+'?title='+params['title']+'&price='+params['price']+'&img_src='+params['img_src'];
});
我不知道您想如何将参数传递到新站点通过url(或通常的js)传递价格等对于商店系统是不安全的。相反,您应该传递ID以从服务器获取数据。使用数据-属性如何?