Can't update data-attribute value

后端 未结 9 1562
北海茫月
北海茫月 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:15

    For myself, using Jquery lib 2.1.1 the following did NOT work the way I expected:

    Set element data attribute value:

    $('.my-class').data('num', 'myValue');
    console.log($('#myElem').data('num'));// as expected = 'myValue'
    

    BUT the element itself remains without the attribute:

    I needed the DOM updated so I could later do $('.my-class[data-num="myValue"]') //current length is 0

    So I had to do

    $('.my-class').attr('data-num', 'myValue');
    

    To get the DOM to update:

    Whether the attribute exists or not $.attr will overwrite.

提交回复
热议问题