【问题标题】:jQuery selecting divs when there are 2.有 2 个时 jQuery 选择 div。
【发布时间】:2012-08-27 12:58:17
【问题描述】:

先告诉你一些关于我的剧本的事情。它创建好友请求的 php/html 渲染。您可能知道,一次可以有 1 到多个好友请求。现在我的 jQuery 脚本只适用于第一个,所以我确实需要一些指导来让两个对多个功能正常工作。

请注意,我的 div 对每个人都有不同的 id。

首先是我的 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>

第二个是我的 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();
        });

});

如何使此代码适用于两个或多个好友请求。

PS。我对 jquery 还很陌生,所以还在学习。找不到这方面的教程。

感谢我能得到的任何帮助。

【问题讨论】:

标签: jquery field


【解决方案1】:

.click() 事件处理程序绑定到类friendConfirm 的所有元素,然后将this.id 引用的被点击元素的id 连接到$.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();
    });
});​

【讨论】:

  • 甜蜜。不确定是否存在。很高兴知道以供将来参考!
  • 是的,.click() 会将事件处理程序绑定到与选择器匹配的 所有 元素,因此无需单独绑定到每个 id
猜你喜欢
  • 2015-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
相关资源
最近更新 更多