簡體   English   中英

如何使用javascript / jquery增加點擊次數?

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

我有一個循環中創建的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增加一個。

換句話說我每次點擊一個鏈接,我得到place從1開始遞增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) {
        ...
      }
    });

  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM