【发布时间】:2021-01-07 15:23:04
【问题描述】:
我想获取图像元素的图像源。我现在拥有的是:
HTML
<div class="item">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Tomato_je.jpg" alt="" id="item-img">
<h1>Tomato</h1>
<h2>₹50</h2>
<a href="#0" class="cd-add-to-cart js-cd-add-to-cart btn-grad" data-name="Tomato" data-price="50">Add To Cart</a>
</div>
Javascript
function addProduct(target) {
//alert(target.getAttribute('data-name'), true)
// this is just a product placeholder
// you should insert an item with the selected product info
// replace productId, productName, price and url with your real product info
// you should also check if the product was already in the cart -> if it is, just update the quantity
productId = productId + 1;
productName=target.getAttribute('data-name'), true;
productPrice=target.getAttribute('data-price'),true;
var productAdded = '<li class="cd-cart__product"><div class="cd-cart__image"><a href="#0"><img src="assets/img/product-preview.png" alt="placeholder"></a></div><div class="cd-cart__details"><h3 class="truncate"><a href="#0">'+productName+'</a></h3><span class="cd-cart__price">'+productPrice+'</span><div class="cd-cart__actions"><a href="#0" class="cd-cart__delete-item">Delete</a><div class="cd-cart__quantity"><label for="cd-product-'+ productId +'">Qty</label><span class="cd-cart__select"><select class="reset" id="cd-product-'+ productId +'" name="quantity"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select><svg class="icon" viewBox="0 0 12 12"><polyline fill="none" stroke="currentColor" points="2,4 6,8 10,4 "/></svg></span></div></div></div></li>';
cartList.insertAdjacentHTML('beforeend', productAdded);
};
我可以获取商品的名称和价格,但无法获取图片来源。我的代码输出如下图所示,我希望将图像放在红色圆圈区域中
【问题讨论】:
-
productName=target.getAttribute('data-name'), true;为什么会有逗号和true? -
@ epascarello 实际上这是从网站复制的代码,我改变了一些东西,但对我来说,图像并没有像给定的图像那样显示。
-
代码中没有您选择图像的位置。
-
我不知道选择它你能帮我吗??
标签: javascript html image getattribute