Can't update data-attribute value

后端 未结 9 1568
北海茫月
北海茫月 2020-11-27 17:11

Although there are some examples about this on the web, it does not seem to work correctly. I can\'t figure out the problem.

I have this simple html

         


        
9条回答
  •  伪装坚强ぢ
    2020-11-27 17:26

    If we wanted to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

    JavaScript

    
    

    Through jQuery

    // Fetching data
    var fruitCount = $(this).data('fruit');
    
    // Above does not work in firefox. So use below to get attribute value.
    var fruitCount = $(this).attr('data-fruit');
    
    // Assigning data
    $(this).data('fruit','7');
    
    // But when you get the value again, it will return old value. 
    // You have to set it as below to update value. Then you will get updated value.
    $(this).attr('data-fruit','7'); 
    

    Read this documentation for vanilla js or this documentation for jquery

提交回复
热议问题