Data attribute value updated by jquery is not visible in DOM

后端 未结 2 1342
死守一世寂寞
死守一世寂寞 2020-11-30 07:28

I am updating a data attribute by jQuery, Like:

jQuery(\'div\').data(\'hidden\', \'true\');
alert(jQuery(\'div\').data(\'hidden\'));

Data a

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 08:13

    I was beating around the bush so badly :( and able to solve the problem. Seams like we can't do achieve this using the jquery data method if the html is dynamic and the data attribute changed later after accessing the first time.

    According to jQuery.data()

    The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

    So what I did is, changed it to attr method which won't give you the parsed value for integer, so you have to use '+' operand to convert like:

    + myElement.attr('data-index');
    

    Note: You have to be careful, it will convert the result to NaN if there is any string in the data attr. BTW it's your choice of implementation of the code.

提交回复
热议问题