简体   繁体   中英

How to increment number on click by using javascript / jquery?

i have 5 links that gets created in a loop ($.each):

$.each(data, function(index, element) {
name = element.name;
id = element.id;
    $('<a href="#" id="'+id+'" onClick="submitNotification('+id+');">'+name+'</a>')

});

in my case this will create 5 links:

<a href="#" id="1" >name1</a>
<a href="#" id="2" >name2</a>
<a href="#" id="3" >name3</a>
<a href="#" id="4" >name4</a>
<a href="#" id="5" >name5</a>

and

function submitNotification(cdata){
alert('you selected '+cdata->name+' on '+place+'place');

         $.ajax({ 
    type: 'POST', 
    url: 'http://www.example.com/test.php', 
    data: cdata,
    dataType:'json',
    success: function (data) {
    ...
    }

});
}

what i want is when i click on any link to get the alert: you selected name2 on 1 place . Then if i click another link to get the same alert but with the place var incremented by one.

In other words Each time i click on a link i get place starting at 1 and increment 1 until it gets to 5

then send data to a ajax post.

Now, there are 2 things i have dificulty doing:

1. placing id and name inside an javascript object so i they both can be available to send to the ajax post
2. how do i do the increment so that no matter on what link i click first the countwill start from 1. 

any ideas? knowing this will help me a lot.

THanks

Declare the place counter and data container outside the function:

var place = 0, postData = [];

function submitNotification(cdata){
  place++;
  alert('you selected '+cdata->name+' on '+place+'place');

  postData.push(cdata);

  if (place == 5) {

         $.ajax({ 
    type: 'POST', 
    url: 'http://www.example.com/test.php', 
    data: { places: postData },
    dataType:'json',
    success: function (data) {
        ...
      }
    });

  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM