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

$(this) does not work inside onclick attribute

<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>