我有一个循环中创建的5个链接($ .each):

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

});


就我而言,这将创建5个链接:

<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>




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) {
    ...
    }

});
}


我想要的是当我单击任何链接以获取警报时:you selected name2 on 1 place。然后,如果我单击另一个链接以得到相同的警报,但place var递增一个。

换句话说,每次我单击链接时,我都会从1开始获得place,并递增1,直到达到5。

然后将数据发送到ajax帖子。

现在,我很难做到两件事:

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.


有任何想法吗?知道这将对我有很大帮助。

谢谢

最佳答案

在功能之外声明位置计数器和数据容器:

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) {
        ...
      }
    });

  }

}

07-25 21:15
查看更多