2010-02-20 78 views
0

我有一个页面,我显示的用户列表和旁边的每个用户 - 有“添加为朋友”链接。Jquery提交多个链接

现在当用户点击这个“Add as Friend”链接时 - 我想调用Jquery并将该请求提交给后端PHP。

通常我与jQuery的经验涉及其在该页面的单一形式,并通过jQuery 提交该表格 - 每个表格都有一个ID - 使用该ID我称之为提交功能$(“#invite_form”)提交(函数() - 我以这种方式访问​​表单元素var emailval = $(“#emails”)。val();

但是现在,我没有表单,并且这个朋友列表正在循环中生成。 所以这里是我的疑问

1)我是否需要在循环中为每个href标记创建一个唯一的ID

2)如何更改此$(“#invite_form”)。submit(function() - 它会变成 (“#ahref1”)。click(function()其中ahref1是href标签的唯一ID

3)如何访问在Jquery的功能friend_id领域这是目前在href值类似于HREF =“/行动?friend_id = 32”

不知道如果我要在正确的轨道上 谢谢

回答

1

您可以使用jQuery中的$ .post()或$ .get()提交到后端脚本

举例:

$("#ahref1").click(function(){ 
    var this_friend_id = $(this).prev('input.friend_id').val(); 
    // Assuming that you store the id in a hidden input field like <input type="hidden" class="friend_id" val="32" /> which is defined just before the a href. 
    $.get('/action', { 
    friend_id: this_friend_id 
    }, function(data){ 
     // callback after the ajax request 
     alert("The response is : "+data); 
    }); 
}); 

这应该可以解决问题。

+0

感谢GeekTantra - 但我该如何处理不同的ahref id 就像我说的 - 这些是在循环中生成的 - 所以会有10个不同的行。现在,即使我为每个ahref标记创建了一个唯一的ID - 我将需要创建10个不同的函数,如 $(“#ahref1”)。click(function() $(“#ahref2”)。click(function ) $( “#ahref3”)。点击(函数() $( “#ahref4”)。点击(函数() 类似的问题,我会与朋友ID输入字段 感谢 – Rick 2010-02-20 09:39:59

+1

我来补充而不是我自己的答案,因为GeekTantra几乎完美无缺,jQuery的神奇之处在于,选择器可以匹配多个元素,因此只需一个点击函数即可为所有链接提供服务请注意,ID不会出现在内部GeekTantra的函数 - 它只是使用“this”来知道哪个链接被点击了,所以如果你在代码的开头改变“$(”#ahref1“)”为“$(”id^='ahref'“)”该点击功能将适用于任何id为“ahref”开头的元素,并且它适用于所有链接。 – 2010-02-20 09:51:49

+0

Thankyou共享该信息 – Rick 2010-02-20 10:15:11

0

1)不,你不知道。你总是可以创建一个jQuery循环,有。每(),并自定义脚本像

$(document).ready({ 
    $('#friend_list a').each(function() { 
     // Point to current <a> 
     var $this = $(this); 
     // ... your code for each a in your list 
    }); 
}); 

2)您可以更改提交功能类似

$(document).ready({ 
    $('#friend_list a').each(function() { 
     var $this = $(this); 
     // Save current href 
     var href = $this.attr('href'); 
     // When user click 
     $this.click(function(e) { 
      // Doesn't follow the href path 
      e.preventDefault(); 
      // ... your custom operation here 
     }); 
    }); 
}); 

3)您可以使用正则表达式

$(document).ready({ 
    $('#friend_list a').each(function() { 
     var $this = $(this); 
     var href = $this.attr('href'); 
     $this.click(function(e) { 
      e.preventDefault(); 
      // Assuming your link is in form "/action?friend_id=32" 
      var re = new RegExp("\d+"); 
      var id = re.exec(href); 
      // I prefer AJAX method, this is just a sample, to complete 
      $.post('/action', 
        { friend_id: id }, 
        function(data) { 
         // ... result here 
        }); 
     }); 
    }); 
}); 
+0

您的代码示例完美匹配我的需求 Thankyou太花时间把它放在一起 欣赏它 – Rick 2010-02-20 10:15:52

+0

不客气。 – 2010-02-20 12:52:21