user5670402
user5670402

Reputation:

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

This is my javascript function between <script> tags. When it called id shown as undefined. Why $(this) is not working?

Upvotes: 1

Views: 912

Answers (1)

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

You have to pass the element as the parameter of call() function like following.

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

Upvotes: 5

Related Questions