Uncaught TypeError: Failed to execute 'setAttribute'(setAttribute定義屬性錯誤)


"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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM