2012-01-30 76 views
1

我有5個鏈接,獲取一個循環($。每個)創建:如何通過使用javascript/jquery增加點擊數量?

$.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開始遞增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. 

什麼想法?知道這將幫助我很多。

感謝

+0

什麼,如果相同的鏈接被點擊twince ???或五次? – 2012-01-30 08:54:54

+0

數字ID屬性是非法的,它們必須以a-z或A-Z開頭,否則可能會遇到問題。這是onclick,而不是onClick – devnull69 2012-01-30 09:10:44

回答

0

聲明地方計數器和數據容器之外的功能:

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

    } 

} 
+0

這工作,我替換'place;'用'place ++;'。 THnaks – Patrioticcow 2012-01-31 05:41:27

+0

@Patrioticcow:當然。我記得輸入那個,但我一定錯過了關鍵... – Guffa 2012-01-31 05:43:39