开发者问题收集

javascript 不读取 src 类型,总是出现错误

2023-03-30
64

这是 javascript 出错的部分

function addCartClicked (event) {
    var button = event.target;
    var shopProducts = button.parentElement;
    var title = shopProducts.getElementsByClassName("product-name")[0].innerText;
    var price = shopProducts.getElementsByClassName("price")[0].innerText;
    var productImg = shopProducts.getElementsByClassName("product-image")[0].src;

    console.log(title, price, productImg);
  }

这是 HTML 部分

<section class="projects" id="section">
<center><h1 class="ourpr">OUR PRODUCTS:</h1></center>
<div class="content">
<li>
<div class="project-card">
<img src="C:\Users\MSI\Documents\INFO\ex4 serie html\TOPG\capolista.png" alt="" class="product-        image" style="width: 360px; height: 348px;">
<div class="project-info">
<strong class="project-title"> <a class="product-name">makrouna fil</a> <a class="price">10$    </a><a class="addcart" align="center">Add to Cart</a>  </strong> </div>
</div>
 </li>

总是出现错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'src')

即使我输入 .innerText 也还是一样,不知道为什么

我尝试用 innerText 替换它,结果还是一样 我尝试输入时不加“.”

var productImg = shopProducts.getElementsByClassName("product-image")[0])

它只显示价格和名称,没有显示图片

2个回答

只需从 img 类中删除空格即可:

<img src="C:\Users\MSI\Documents\INFO\ex4 serie html\TOPG\capolista.png" alt="" class="product-        image" style="width: 360px; height: 348px;">

<img src="C:\Users\MSI\Documents\INFO\ex4 serie html\TOPG\capolista.png" alt="" class="product-image" style="width: 360px; height: 348px;">
function addCartClicked(event) {
    var button=event.target;
    var shopProducts=button.parentElement;
    var title=shopProducts.getElementsByClassName("product-name")[0].innerText;
    var price=shopProducts.getElementsByClassName("price")[0].innerText;
    var productImg=shopProducts.getElementsByClassName("product-image")[0].src;

    console.log(title, price, productImg);
}
document.getElementById('btn').onclick = addCartClicked;
<section class="projects" id="section">
    <center>
        <h1 class="ourpr">OUR PRODUCTS:</h1>
    </center>
    <div class="content">
        <li>
            <div class="project-card">
                <img src="C:\Users\MSI\Documents\INFO\ex4 serie html\TOPG\capolista.png" alt="" class="product-image" style="width: 360px; height: 348px;">
                <div class="project-info">
                    <strong class="project-title"> <a class="product-name">makrouna fil</a> <a class="price">10$    </a><a class="addcart" align="center">Add to Cart</a>  </strong> </div>
            </div>
        </li>
    </div>
    <button id="btn">Click</button>
</section>
Jordy
2023-03-30

请尝试从 <img> 标签中删除 classname 的空格,将其改为 class="product-image" 。不要添加不需要的空格,这不是一个好的做法。

Rini NR
2023-03-30