javascript - How to get data attribute value on click? -
I have a link and when the value of the text and data attribute of a div changes, then it is changing when I pressed So I have another link that I get those converted values. Here's the code:
& lt; One class = "first" href = "#" & gt; Change price & lt; / A & gt; & Lt; One class = "second" href = "#" & gt; Get value & lt; / A & gt; & Lt; Div class = "value" data-trial = "test" & gt; Trial & lt; / Div & gt; $ (Document) .ready (function () {$ ('first'). ('Click', function (e) {e.preventDefault (); $ ('.value'). Html ($ (this) Text ()). Attr ('data-test', $ (this) .text ());}); $ ('. Second'). ('Click', function (e) {e.preventDefault () ; $ Value = $ ('. Value'). Text (); $ data = $ ('. Value'). Data ('test'); Alert ($ data);});});
The problem is that after the price changes I can get a new text value of the div but the value of the data attribute remains the same as the DOM load How do I get a new value for the data attribute?
jQuery will retrieve only data -type This method provides if you have not already stored one, that is, when you retrieve the code from .data ('test') To change the attribute to mention, you can call again with the attribute next time:
$ ('.value'). Html ($ (this) .text ()) .removeData ('test') .attr ('data-test', $ (this) .text ());
However, it would be better to just be compatible and use either .attr () or . Data () Get both sets and values:
$ ('. Value'). Html ($ (this) .text ()). Data ('test', $ (this) .text ());
Comments
Post a Comment