开发者问题收集

HTML 的 innerText 未定义,但不应该如此

2022-12-21
179

错误是:

Cannot read properties of undefined (reading 'innerText')

当我尝试运行代码时出现此错误。

var addCart = document.getElementsByClassName("add-cart");

for (var i = 0; i < addCart.length; i++) {
  var button = addCart[i];
  button.addEventListener("click", addCartClicked);
}


function addCartClicked(event) {
  var button = event.target;
  var shopProducts = button.parentElement
  var title = shopProducts.getElementsByClass("product-title")[0].innerText;
  console.log(title);
}
<h4 class="product-title">Breakfast Club Blue Hoodie</h4>
<div class="rating">
  <i class="fa fa-star"></i>
  <i class="fa fa-star"></i>
  <i class="fa fa-star"></i>
  <i class="fa fa-star"></i>
  <i class="fa fa-star"></i>
</div>
<p>$55.00<i class="fa fa-cart-plus add-cart"></i></p>
</div>

我预期“product-title”中的内容会出现在控制台上

2个回答

您单击的图标的父元素是 p 标签,因此您需要再上一级。

var addCart = document.getElementsByClassName("add-cart");
for (var i = 0; i < addCart.length; i++){
    var button = addCart[i];
    button.addEventListener("click", addCartClicked);
}

function addCartClicked(event){
var button = event.target;
var shopProducts = button.parentElement
var grandParent = shopProducts.parentElement
var title = grandParent.getElementsByClassName("product-title")[0].innerText;
console.log(title);
}

或者您也可以这样做:

var shopProducts = button.parentElement.parentElement
PhilCowan
2022-12-21
function addCartClicked(event) {
  var button = event.target;
  var shopProducts = button.parentElement
  var title = button.parentNode.previousElementSibling.previousElementSibling.innerText;
  console.log(title);
}

这不是一个好方法,但可能有助于您获得结果

Ra Zi
2022-12-21