javascript - 单击网格中的任何图像时如何运行函数?

标签 javascript jquery html css

因此,我在“产品网格”中有称为产品的图像 block 。

每个组都有不同的值,虽然它们现在是静态输入的,但我想将来它们都会通过某种适配器添加。在这种情况下,只定义了类,没有定义 ID。

我如何做到这一点,以便在单击图像时,无论它在网格上的任何位置,我都能够检索:

  1. 产品名称 (product_title)
  2. 产品价格 (product_price)
  3. 图片来源(images/product7.jpg);并将其发送到下一页?

一方面,我知道如果设置了id,就可以得到like值内的属性。当数据不在像下面这样的单个标签/元素中时,javascript 是如何编写的?此外,假设我没有定义 id,我如何仅从与单击的图像关联的元素“组”中获取数据?每个“ block ”基本上都有相同的类。

在这种情况下是否不可避免地要为每个副本定义一个 ID?


这是一个 block 的样子,复制了几次:

        <!-- 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>

都在一个

里面
            <div class="row">
                <div class="col">

                    <div class="product_grid">

每个副本都定义了相同的类,只是 innerhtml 值不同,比如价格。然后将这些值发送到另一个页面以执行操作。

最佳答案

使用 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}`);

})

关于javascript - 单击网格中的任何图像时如何运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56652076/

相关文章:

jquery - jqGrid 传递值到表单编辑

html - 如何使用显示 : inline-block when resizing browser? 缩放图像

javascript - jQuery 电话号码屏蔽与正则表达式不起作用

html - 浏览器如何确定什么是 "mobile"站点与什么是 "desktop"站点?

javascript - WebRTC DataChannel 不符合规范?

javascript - 如何将动态段传递给 ember 组件

javascript - JS Class : Difference between ES6 myFunc(){. .} 和 ES5 myFunc = function() {...} 在类声明中

javascript - 使用 javascript 检查 URL 是否存在

javascript - bootstrap-datetimepicker:输入文本框和图标的布局问题

javascript - 我可以将单页应用程序称为 Web 3.0 应用程序吗?