我有流程:
- 用户点击项目(已设置 Postee 对象)
- 用户点击发帖(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
对象?控制台日志返回一个 undefined variable 错误。提前致谢。
最佳答案
问题是因为您在 .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')
}
关于javascript - 使用 jQuery 使用多个 .on() 方法设置和获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31513570/