问题
Let tell you a bit about my script first. It creates a php/html render of the friend requests. As you may know, there can be 1 to many friend requests at a time. Right now my jQuery script only works for the first so I do need some guidance to get the two to many functionality working.
Notice that my div's have a different id for each person.
FIrst here's my html
<div class='fRequest'>
<h3>Pending Friend Requests:</h3><div class='friendRequest' id='0'><img src='[url]' alt='Charles Williamson'/> Charles Williamson<a id='4' class='friendConfirm' href='#'
style='border:1px solid #dadada; background:#fff; margin-left:
10px; line-height: 60px; padding: 4px 4px; color:gray; text-decoration:none;'>
Confirm</a></br></div><div class='friendRequest' id='1'><img src='[url]' alt='Rachel Cole'/> Rachel Cole<a id='5' class='friendConfirm' href='#'
style='border:1px solid #dadada; background:#fff; margin-left:
10px; line-height: 60px; padding: 4px 4px; color:gray; text-decoration:none;'>
Confirm</a></br></div></div>
Second here's my jQuery.
$(document).ready(function(){
$(".friendAdded").css('display', 'none');
var frid = $(".friendConfirm", ".friendConfirm").attr('id');
$(".friendConfirm#"+frid).click(function(){
$.get("JSON/addFriend.php?fid="+frid,
function(data){
$(".friendAdded").append(data);
$(".friendAdded").show() })
});
$(".closeOwe").click(function(){
$(".friendAdded").css('display', 'none')
location.reload();
});
});
How can I make this code work for both or many friend requests.
PS. i'm fairly new to jquery so still learning. Having trouble finding tutorials for this.
THanks for any help I can get.
回答1:
Bind the .click() event handler to all elements with the class friendConfirm, and then concatenate the clicked element's id, referenced by this.id, to the $.get() url:
$(document).ready(function(){
$(".friendAdded").css('display', 'none');
$(".friendConfirm").click(function() {
$.get("JSON/addFriend.php?fid="+this.id,
function(data) {
$(".friendAdded").append(data);
$(".friendAdded").show()
}
);
});
$(".closeOwe").click(function() {
$(".friendAdded").css('display', 'none')
location.reload();
});
});
来源:https://stackoverflow.com/questions/12236841/jquery-selecting-divs-when-there-are-2