js报错之item.getAttribute is not a function

本文记录了一次JavaScript编程中遇到的getAttribute方法错误的问题排查过程。作者尝试从代码中获取一个不存在的属性值,并最终发现该属性未被正确设置。通过逐步调试定位问题,为读者提供了一个实用的调试技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码报错
在这里插入图片描述
解决过程
我想获取item下的属性changePrice,报错
item.getAttribute is not a function,
我就用console.log(item.getAttribute(‘changePrice’));想打印出来这个结果,但是为空,价格非法
在这里插入图片描述

我就去打印上一步的item,一步一步的向上找,最后发现自己的dd容器里面没有这个属性,我只是将js文件里面的数据引用过来而已,没有设置这个changePrice
建议大家如果报错,先查找自己这个里面是否设置这个属性
代码附上

ddNode.setAttribute('changePrice',item.changePrice);
function priceSum(arr){
		// 获取原始价格
		// console.log(arr);
		var price = goodData.goodsDetail.price;
		// 获取价格容器
		var priceNode = document.querySelector('.mainCon .chooseWrap .priceWrap .priceTop .price em');
		arr.forEach(function(item){
			// 在这个循环中 item对应的是 传入数组当中存储的每一个dd元素
			// console.log(item);
			// console.log(item.getAttribute('changePrice'));
			if(item){
				// console.log(item.changePrice);
				price += parseInt(item.getAttribute('changePrice'));
			}
			console.log(price);
		})
		priceNode.innerHTML = price;
	}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值