如何给li标签添加点击事件
有很长一段时间没写博客了,最近做了一个类似于榜单的小需求,遇到了一些小问题,姑且简单的记录一下吧。
- 注:用的vue,手动绘制了个简单的demo,非专业前端制作界面比较简陋,哈哈。
一、HTML demo代码
<div class="box decoration" style=" margin:0 auto">
<h1 style="text-align: center;" >浏览榜单</h1>
<ul id="top_panel" style="margin:0 auto">
//动态增加需要的li
</ul>
</div>
二、JS动态新增li并绑定点击事件
drawPanel: function (data){
$("#top_panel").empty();
var mainPanel = document.getElementById("top_panel");
for(var i=0; i<data.length; i++){
var childDiv = document.createElement("li");
childDiv.style.marginLeft = "-28px";
childDiv.id = data[i].detoxificationCaseId;
childDiv.innerHTML = '<span>'+((this.pageNo-1)*6+i+1)+'</span>'+data[i].caseName
+'<strong class="view_count">'+data[i].viewTimes+' 浏览量</strong>';
mainPanel.appendChild(childDiv);
childDiv.onclick = function ( ) {
//获取添加的li标签的元素值
alert("当前点击记录id:"+this.id);
// window.location.href= "detoxificationDetail.html?detoxificationCaseId=" +this.id ;
}
}
}
- 注:点击事件是在点击之后才触发绑定,之前博主发现直接在
childDiv.onclick = function ( ) {}
中直接将参数绑定对应ID,但是到点击的时候默认携带的id还是列表最终的参数。所以就曲线救国,把id直接设置成了li的模块id,在点击的时候获取本身的id,这样就不会造成错乱了。
三、效果图
- 仅作记录,个人开发所遇所解,希望对你有帮助!如有错误还望指正,谢谢!一只不断前进的全栈码畜!