一段简单的代码记录如何通过 js 给 HTML 设置自定义属性,并且通过点击事件获取到所设置的自定义属性值
for (var i = 0; i <= 5; i++) { const divJoinDay = document.createElement("div"); divJoinDay.style.padding = "6px 30px"; divJoinDay.style.backgroundColor = "#ffffff"; divJoinDay.style.color = "#000"; divJoinDay.style.borderBottom = "solid 1px #e6e6e6"; if (i === 0) { divJoinDay.innerHTML = "待 选"; } else { divJoinDay.innerHTML = "第 "+ i +" 天"; } divJoinDay.setAttribute("data-day", i); divJoinDay.onmouseover = (e) => { divJoinDay.style.backgroundColor = "#f39800"; }; divJoinDay.onmouseout = (e) => { divJoinDay.style.backgroundColor = "#ffffff"; }; divJoinDay.onclick = (e) => { const dayId = e.target.getAttribute("data-day"); alert("第 "+ dayId +" 天"); // 阻止冒泡事件 e.cancelBubble = true; }; divPullDown.appendChild(divJoinDay); }
设置值:
document.setAttribute("data-day", i);
点击事件获取值
e.target.getAttribute("data-day");