"click 1 to get 1, click 2 to get 2"

How can I fix it to click 1 to get 1 and click 2 to get 2?

$(function() {
  $('div.abox > a').on('click', function(e) {
    e.preventDefault();
  });
});
$('div.abox').click(function() {
  $('div.abox').css('display', 'none');
  $('div.page').css('display', 'block');
  page();
});

var num = 1;
var p = {
  1: {
    'title': 'title1',
    'img': '1111',
    'explain': 'ex1'
  },
  2: {
    'title': 'title2',
    'img': '2222',
    'explain': 'ex2'
  },
  3: {
    'title': 'title3',
    'img': '3333',
    'explain': 'ex3'
  },
  4: {
    'title': 'title4',
    'img': '4444',
    'explain': 'ex4'
  }
}

function page() {
  var abox = $('div.abox > a');

  $("#title").html(p[num]["title"]);
  $("#img").html(p[num]["img"]);
  $("#explain").html(p[num]["explain"]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="abox">
  <a href="" onclick="page();">1</a>
  <a href="" onclick="page();">2</a>
  <a href="" onclick="page();">3</a>
  <a href="" onclick="page();">4</a>
</div>
<div class="page">
  <h2 id="title">title</h2>
  <div id="img">img</div>
  <p id="explain">explain</p>
</div>

34 thoughts on “"click 1 to get 1, click 2 to get 2"”

  1. You can use .text() to get text of a tag which is clicked and then use same to show your values .

    Demo Code :

    var p = {
      1: {
        'title': 'title1',
        'img': '1111',
        'explain': 'ex1'
      },
      2: {
        'title': 'title2',
        'img': '2222',
        'explain': 'ex2'
      },
      3: {
        'title': 'title3',
        'img': '3333',
        'explain': 'ex3'
      },
      4: {
        'title': 'title4',
        'img': '4444',
        'explain': 'ex4'
      }
    }
    
    
    $(function() {
      $('div.abox > a').on('click', function(e) {
        e.preventDefault();
        console.log($(this).index() + 1) //or this way
        console.log($(this).data('id')) //or this way
        var num = $(this).text(); //or this way
        $("#title").html(p[num]["title"]);
        $("#img").html(p[num]["img"]);
        $("#explain").html(p[num]["explain"]);
      });
      $('div.abox > a:eq(0)').trigger('click')
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="abox">
      <a href="" data-id='1'>1</a>
      <a href="" data-id='2'>2</a>
      <a href="" data-id='3'>3</a>
      <a href="" data-id='4'>4</a>
    </div>
    <div class="page">
      <h2 id="title">title</h2>
      <div id="img">img</div>
      <p id="explain">explain</p>
    </div>
    Reply

Leave a Comment