jQuery selecting divs when there are 2.

情到浓时终转凉″ 提交于 2019-12-24 02:18:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!