使用 jQuery 使用多个 .on() 方法设置和获取对象

Set and Get Object with multiple .on() methods using jQuery

我有流程:

  1. 用户点击项目(已设置Postee对象)
  2. 用户点击post(Postee对象为GET,用于提交)

我的代码如下所示:

$(document).ready(function () {

    var postee;

    //SHARE FEED ITEM START
    $(document).on('click', '.feed-item-share', function(e){

        var $this = $(this);
        var feed_item = $this.closest('.feed-item');

        var postee = {
            object_id : feed_item.attr('data-feed-item-object-id'),
            type : feed_item.attr('data-feed-item-type'),
            user_id : feed_item.attr('data-feed-item-user-id'),
            id : feed_item.attr('data-feed-item-postee-id'),
            name : feed_item.attr('data-feed-item-postee-name'),
            img_id : feed_item.attr('data-feed-item-postee-img-id')
        }

        console.log("Postee: "+postee);
    });

    $('#share_post_button').on('click', function (e) {

        console.log(postee);

        e.preventDefault();
        console.log('Post Click');
    });
});

有谁知道为什么我在单击 #share_post_button 时无法获取 postee 对象?控制台日志返回一个未定义的变量错误。提前致谢。

问题是因为您在 .feed-item-share 点击处理程序中重新定义了 postee 变量,所以它超出了 #share_post_button 点击处理程序的范围。删除 var。另请注意,您应该使用 data() 来检索 data-* 属性,因为它是从 jQuery 的内部缓存中读取并保存 DOM 次读取。

试试这个:

postee = {
    object_id : feed_item.data('feed-item-object-id'),
    type : feed_item.data('feed-item-type'),
    user_id : feed_item.data('feed-item-user-id'),
    id : feed_item.data('feed-item-postee-id'),
    name : feed_item.data('feed-item-postee-name'),
    img_id : feed_item.data('feed-item-postee-img-id')
}