Accessing data attribute using jquery returns undefined?

后端 未结 2 1076
傲寒
傲寒 2021-02-05 18:55

Inside my view i have a button as follow:

2条回答
  •  礼貌的吻别
    2021-02-05 19:29

    In your current script, $(this) refers to the Window object (not your button) which does not have a data- attribute so its undefined.

    You could solve this by passing the element to the function

    
    
    function updateClick(element) {
        var id = $(element).data('assigned-id');
        ....
    

    However a better approach is to use Unobtrusive Javascript rather than polluting your markup with behavior.

    
    
    $('#mybutton').click(function() {
        var id = $(this).data('assigned-id'); // $(this) refers to the button
        ....
    });
    

提交回复
热议问题