首页 > 其他 > 详细

Uncaught TypeError: Failed to execute 'setAttribute'(setAttribute定义属性错误)

时间:2021-03-27 22:20:49      阅读:30      评论:0      收藏:0      [点我收藏+]

"Uncaught TypeError: Failed to execute ‘setAttribute‘ on ‘Element‘: 2 arguments required, but only 1 present."意思是setAttribute需要传入两个参数,但仅传入一个。该错误是由于setAttribute里传入的参数不全或者错误导致。

<body>
	<div class="contain">
		<div class="shop">
			
		</div>
		<div class="button copy">
			<input type="checkbox" />
			<label>全选</label>
			<label>总价:<span id="allPrice">0</span>元</label>
			<label>结算:<span>0</span>元</label>
		</div>
	</div>
</body>
shopContain = document.getElementsByClassName("shop")[0];//shop节点
subBtn=document.getElementsByClassName(‘sub‘);//sub按钮节点(通过拼接字符串添加)
var arrObj = [
        {
        	shopName:"钻石",
        	shopImg:"img/hot1.jpg",
        	shopPrice:1000,
        	shopCount:1,
        },
        {
        	shopName:"黄金",
        	shopImg:"img/hot1.jpg",
        	shopPrice:2000,
        	shopCount:1,
        }
    ]
//拼接字符
for (var i = 0; i < arrObj.length; i++) {
    var itemObj=arrObj[i];
    var chcked =‘<input type="checkbox" />‘;
    var shopNameStr = "<label>商品名称:"+itemObj["shopName"]+"</label>";
    var shopImgStr = "<label><img src="+itemObj["shopImg"]+"></label>"
    var shopPriceStr = "<label>价格:<span>"+itemObj["shopPrice"]+"元</span></label>";
    var shopCountStr = ‘<label>数量:<button class="sub" disabled="disabled" >-</button><span>‘+itemObj["shopCount"]+‘个</span><button class="add">+</button></label>‘;
    var divStr = "<div>"+chcked+shopNameStr+shopImgStr+shopPriceStr+shopCountStr+"</div>";
    shopContain.innerHTML+= divStr;
}

for (var i = 0; i < subBtn.length; i++) {
    subBtn[i].onclick=sub;
    console.log(subBtn[i])
    //对于自定义的属性,应该通过setAttribute方法来添加到元素节点中,否则就无法获取该属性,要想获取自定义属
    //性的值,应该在setAttribute(参数1,参数2)中传入参数2的值(注:参数1:自定义的属性,参数2:给自定义属
    //性设置的值),这样才能subBtn.index,获取自定义属性index的值,可以写成以下写法
    subBtn[i].setAttribute("index",i)
    subBtn.index=i
    addBtn[i].onclick=add;
}

Uncaught TypeError: Failed to execute 'setAttribute'(setAttribute定义属性错误)

原文:https://www.cnblogs.com/peng-blogs/p/14586311.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!