動態遍歷複選框且id名與其label標籤for屬性一一繫結
阿新 • • 發佈:2019-01-29
圖片展示:
css程式碼:
注:label標籤定位在複選框上
input[type="checkbox"]{ display: none; } label{ position: relative; display: inline-block; z-index: 1; border: 1px solid #b8b8b8; margin-left: 10px; border-radius: 4px; width: 12px; height: 12px; cursor: pointer; top:30px; }
.box{
position: absolute;
z-index: 0;
left: -20px;
top: -20px;
}
js程式碼:
//json資料:
var orderInfo = { "pros": [ { "userName": "zhangsan", "name": "PLA", "lenght": "3.05", "width": 5.81, "height": 1.96, "price": 25, "count": 1, "owner": "1" }, { "userName": "lisi", "name": "PLA", "lenght": "3.05", "width": 5.81, "height": 1.96, "price": 25, "count": 1, "owner": "1" }, ], }
var datainfo=orderInfo.pros;
//動態遍歷複選框和label標籤:
$.each(datainfo ,function(i,e){ //data是json資料
var $li = '<li><input type="checkbox" class="box"><label class="boxlabel"></label></li>';
//使用動態資料舉例
var $p = '<p>' + e.price + '</p>'
//將p標籤append到頁面所需標籤內即可
$suibian.append($p);
})
//複選框id名與其label標籤for屬性一一繫結
$box = $('.box');
$box.each(function (v) {
$(this).attr("id","box"+v);
$(this).next('label').attr("for","box"+v);
})