的JavaScript的getAttribute在图像元素的方法

问题描述

我想获得的图像元素的图像源。我现在拥有的是:

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);
};

我能够获得该项目的名称和价格,但没能获得图像源。我的代码输出是像下面的图像中,并且我想有图像中的红色圆形区域

image

解决方法

所以你要链接的参考。该图像是兄弟,所以你需要一种方法来引用它。最简单的方法是选择他们的共同的父和比选择该图像。

var parentElement = target.closest(".item");
var image = parentElement.querySelector("img");
console.log(image);

其他说明。摆脱,true上的所有线路。并声明变量。

var productId = 0;
function addProduct(target) {
  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");
  console.log(productName,productPrice,imgSrc);
};

document.querySelector(".cd-add-to-cart").addEventListener("click",function () {
  addProduct(this);
});
img { width: 100px; }
<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>