javascript - 无法使用 javascript 访问我的 html 部分中的动态 ID
问题描述
我知道一点javascript和jquery。在这段代码中,我创建了一个动态 id="nm{{product.id}"。`
<div class="row">
{% for product in product_objects %}
<div class="col-md-3">
<div class="card">
<img src="{{product.image}}" alt="" class="card-img-top">
<div class="card-body">
<div id="nm{{product.id}}" class="card-title">
{{ product.title }}
</div>
<div class="card-text">
{{ product.price }} tk
</div>
<a href="/{{product.id}}" class="btn btn-warning" name="button">View</a>
<button id="{{product.id}}" class="btn atc btn-warning" name="button">Add to cart</button>
</div>
</div>
</div>
{% endfor %}
</div>`
这是我的js部分:
DisplayCart(cart);
function DisplayCart(cart){
//console.log(cart);
var cartString = "";
cartString += "<h5>This is your cart</h5>";
var cartIndex=1;
for(var x in cart){
//console.log(x);
cartString += cartIndex;
cartString += document.getElementById("nm"+x).innerHTML + "Quantity"+ cart[x] +"</br>";
cartIndex+=1;
}
$('[data-toggle="popover"]').popover();
document.getElementById("cart").setAttribute('data-content',cartString);
}
但控制台显示以下错误:未捕获的类型错误:无法读取 null 的属性“innerHTML” 我如何对 id 使用 innerHTML 功能?完整脚本:有我的购物车。购物车是一个 JSON 对象并使用 localStorage 来存储购物车。
<script type="text/javascript">
//console.log("working");
if(localStorage.getItem('cart')==null){
var cart={};
}
else{
cart=JSON.parse(localStorage.getItem('cart'));
}
$(document).on('click','.atc',function(){
console.log("the atc button is clicked");
var item_id = this.id.toString();
console.log(item_id);
if(cart[item_id] != undefined){
cart[item_id]=cart[item_id]+1;
}
else{
cart[item_id]=1;
}
//console.log(cart);
localStorage.setItem('cart',JSON.stringify(cart));
document.getElementById("cart").innerHTML = "Cart("+ Object.keys(cart).length+")";
//console.log(Object.keys(cart).length);
});
/* $(function () {
$('[data-toggle="popover"]').popover()
document.getElementById("cart").setAttribute('data-content','<h5>This is your cart</h5>')
});*/
DisplayCart(cart);
function DisplayCart(cart){
//console.log(cart);
var cartString = "";
cartString += "<h5>This is your cart</h5>";
var cartIndex=1;
for(var x in cart){
//console.log(x);
cartString += cartIndex;
cartString += document.getElementById("nm"+x).innerHTML + "Quantity"+ cart[x] +"</br>";
cartIndex+=1;
}
$('[data-tog
gle="popover"]').popover();
document.getElementById("cart").setAttribute('data-content',cartString);
}
</script>
解决方案
推荐阅读
- python - 通过迭代创建字典同时更新值的 Pythonic 方法?
- javascript - 当页面完全加载时,我如何告诉 puppeteer?
- excel - 使用 if 函数从列中提取日期(如果它存在)或另一个(如果它在 excel 中缺失)
- java - 如何制作一种从 x 和 o 中创建模式的方法?
- progressive-web-apps - 网页调用GameClient的setViewForPopups实现自动登录
- reactjs - 下一个 js 应用程序(在 docker 容器内运行)无法加载位于公共目录中的静态文件图像
- ruby-on-rails - Rails AWS 播种图像 URL 不起作用
- reactjs - RxJS 和重复事件
- android-jetpack-navigation - NavDeepLinkBuilder 上缺少 setDestination 方法
- while-loop - 如何在程序中添加计时器?