Data attribute value updated by jquery is not visible in DOM

浪尽此生 提交于 2019-11-26 11:13:43

问题


I am updating a data attribute by jQuery, Like:

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

Data attribute value got changed and returned new value which is true but DOM is still showing the old value which is false.


回答1:


When you use .data() to update a data value, it is updating internal object managed by jQuery, so it will not be updated in the data-* attribute




回答2:


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.



来源:https://stackoverflow.com/questions/17667732/data-attribute-value-updated-by-jquery-is-not-visible-in-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!