<head>
<script>
function call() {
var id = $(this).data("id");
alert(id);
}
</script>
</head>
<body>
<div data-id="5" onclick="call();"></div>
</body>
Run Code Online (Sandbox Code Playgroud)
这是我在<script>标签之间的javascript功能.当它被称为id显示为undefined.为什么$(this)不工作?
您必须将元素作为call()函数的参数传递,如下所示.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function call(elm) {
var id = $(elm).data("id");
alert(id);
}
</script>
</head>
<body>
<div data-id="5" onclick="call(this);">Click Here</div>
</body>Run Code Online (Sandbox Code Playgroud)