$(this) 在 onclick 属性中不起作用

$(this) does not work inside onclick attribute

本文关键字:属性 不起作用 onclick this      更新时间:2024-03-25
<head>
    <script>
        function call() {
            var id = $(this).data("id");
            alert(id);
        }
    </script>
</head>
<body>
    <div data-id="5" onclick="call();"></div>
</body>

这是我在<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>