有时候我们需要在点击一个按钮时得到他的id或class并对它进行操作,经过在网上查找,我总结了以下一些获取当前id与class的方法。
一、JS原生方法
this.id
this.className
二、jquery中的方法
($(this).attr('id'))
$(this).attr("class")
三、利用target 事件属性
target 事件属性可返回事件的目标节点(触发该事件的节点),如生成事件的元素、文档或窗口。
语法:event.target
获取id:event.target.id
获取text:event.target.textContent
获取class:event.target.className
获取value:event.target.value
(尽量使用event.target.id,不要使用this.id。
当使用事件委托的时候,this指向的是绑定监听事件的元素,而非被点击的元素。event.target.id则始终指向被点击的元素)