码迷,mamicode.com
首页 > Web开发 > 详细

一段简单的代码记录如何通过 js 给 HTML 设置自定义属性,并且通过点击事件获取到所设置的自定义属性值

时间:2018-08-30 12:55:04      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:code   事件   pen   div   获取值   冒泡   down   innerhtml   简单的   

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

 

一段简单的代码记录如何通过 js 给 HTML 设置自定义属性,并且通过点击事件获取到所设置的自定义属性值

标签:code   事件   pen   div   获取值   冒泡   down   innerhtml   简单的   

原文地址:https://www.cnblogs.com/liugx/p/9559452.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!