2012-01-30 92 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