jQuery Method How to - Save data with data() method








Question

We would like to know how to save data with data() method.

Answer


<!--   w  w w .  j a  v  a2s  .  c o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(window).load(function(){

    $('.idTabs li a').on("click", function() {
      var $idTabs = $(".idTabs");
      var clicked = $idTabs.data("clicked");
      if (!clicked) { 
        $idTabs.data("clicked", true);
        console.log('First click');
      } else {
        console.log('Not the first click');
      }
    });
});
</script>
</head>
<body>
  <ol class="idTabs">
    <li><a href="#">a</a></li>
    <li><a href="#">b</a></li>
    <li><a href="#">c</a></li>
  </ol>
</body>
</html>

The code above is rendered as follows: