如何给html元素的onclick事件传递参数(即如何获取html标签的data-*属性)

时间:2023-03-08 21:55:33

  现在做的一个小系统为了达到领导所说的很炫的效果有用到Metro UI CSS,但是因为如何给每个磁贴(div标签)的click事件传递参数折腾了蛮久(偶是菜鸟),后来终于找到一个解决方案即通过data-*属性,下面分别为jQuery和js实现:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jquery/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".title").click(function(){
var id=$(this).data("id");
var name=$(this).data("name");
alert("Id: "+id+" ; Name: "+name);});
}); function onClick(e){
var id=e.getAttribute("data-id");
var name=e.getAttribute("data-name");
alert("Id: "+id+" ; Name: "+name);
}
</script>
</head>
<body>
<div class="title" data-id="1" data-name="Microsoft">Click Me</div>
<div id="add" data-id="2" data-name="Google" onclick="onClick(this)">Click Me</div>
</body>
</html>

参考:Getting data-* attribute for onclick event for an html element