图像元素中的JavaScript getAttribute()方法
我想得到一个图像元素的图像源。我现在得到的是: Html图像元素中的JavaScript getAttribute()方法,javascript,html,image,getattribute,Javascript,Html,Image,Getattribute,我想得到一个图像元素的图像源。我现在得到的是: Html 番茄 ₹50 Javascript 功能添加产品(目标){ //警报(target.getAttribute('data-name'),true) //这只是一个产品占位符 //您应该插入包含所选产品信息的项目 //用真实的产品信息替换productId、productName、price和url //您还应该检查产品是否已经在购物车中->如果已经在购物车中,只需更新数量即可 productId=productId+1; produc
番茄
₹50
Javascript
功能添加产品(目标){
//警报(target.getAttribute('data-name'),true)
//这只是一个产品占位符
//您应该插入包含所选产品信息的项目
//用真实的产品信息替换productId、productName、price和url
//您还应该检查产品是否已经在购物车中->如果已经在购物车中,只需更新数量即可
productId=productId+1;
productName=target.getAttribute('data-name'),true;
productPrice=target.getAttribute('data-price'),true;
var PRODUCTADED=''+productPrice+'Qty123456789 ;
cartList.insertAdjacentHTML('beforeend',productAdded);
};
我可以得到项目的名称和价格,但无法获得图像源。我的代码的输出如下图所示,我希望图像位于红色圆圈区域
这样您就有了对链接的引用。该图像是同级图像,因此您需要一种方法来引用它。最简单的方法是选择它们的公共父对象,然后选择图像
var parentElement = target.closest(".item");
var image = parentElement.querySelector("img");
console.log(image);
其他注释。去掉所有行上的,true
。并声明变量
var productId=0;
功能添加产品(目标){
productId=productId+1;
var productName=target.dataset.name;
var productPrice=target.dataset.price;
var parentElement=target.closest(“.item”);
var image=parentElement.querySelector(“img”);
var imgSrc=image.getAttribute(“src”);
log(productName、productPrice、imgSrc);
};
document.querySelector(“.cd add to cart”).addEventListener(“单击”,函数(){
添加产品(本);
});代码>
img{宽度:100px;}
番茄
₹50
productName=target.getAttribute('data-name'),true代码>为什么有一个逗号和true?@epascarello实际上这是从一个网站复制的代码,我做了一些更改,但对我来说,图像没有显示在给定的图像中。没有在代码中的任何位置选择图像。我不知道如何选择它。你能帮我吗??