Sunday, 15 June 2014

javascript - jQuery dynamically update data keys & values -


I am trying to create a function that dynamically receives all the data-attributes from an element. To:

  & lt; Button id = "button" data-key1 = "title" data-key2 = "content" & gt; Button 1 & lt; / Button & gt; & Lt; Button id = "changeButtonData" & gt; Change the data for button 1 & lt; / Button & gt;   
  $ (document) .on ('click', '#button', function (e) {e.preventDefault () ; $ Button data = $ (this) .data (); console.log ($ button data);} $ (document) .on ('click', '#changebuttondata', function (e) {e.preventDefault (); Data ('data-key1', 'new title'); // Data data on data store $ $ ('# button'). Data ('data-key3', 'new');}   

The problem is, if I click on the first button and check the console log, then it will be data-key1 = "title" / code> and data- Key2 = "content"

and if I later Click the second button, and again click on the first button to re-ignore the console logging, the new replacement data-attributes or new data-tags can not be displayed.

Someone How can I find out how to solve it?

The problem is that when you < Code> data attribute, then you should leave data - prefix, eg: $ ('# button'). Data ('key3', 'new'); Try it:

  $ (document) .on ('click', '#changebuttondata', function (e) {e.preventDefault (); $ ('# button' ) .data ({'key1': 'new title', 'key3': 'new'});};  


No comments:

Post a Comment