Accessing data attribute using jquery returns undefined?

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

Inside my view i have a button as follow:

2条回答
  •  一向
    一向 (楼主)
    2021-02-05 19:27

    When reading data attributes using data() you need to remove the - and camel case the value. So you want:

    var id = $(this).data('assignedId');
    

    the docs on data() show this:

    As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

    For example, given the following HTML:

    All of the following jQuery code will work.

    $( "div" ).data( "role" ) === "page";
    $( "div" ).data( "lastValue" ) === 43;
    $( "div" ).data( "hidden" ) === true;
    $( "div" ).data( "options" ).name === "John";
    

    The second statement of the code above correctly refers to the data-last-value attribute of the element. In case no data is stored with the passed key, jQuery searches among the attributes of the element, converting a camel-cased string into a dashed string and then prepending data- to the result. So, the string lastValue is converted to data-last-value.


    I didn't notice how your binding the click event. If you want to use $(this) you have to bind the event using jquery. So you need:

    
    
    $(window).ready(function() {
         //bind the event using jquery not the onclick attribute of the button
         $('#button').on('click', updateClick);
    
    });
    
    
    function updateClick() {
        alert($(this).data('assignedId'));
    }
    

    Working fiddle

提交回复
热议问题