我的代码有问题:
我通过接受好友请求来构建通知。然后我可以在三种操作之间进行选择(接受、拒绝或阻止)。
HTML
<div class="pull-right">
<a href="#" title="{{_ "notifications.accept"}}" id="ok-btn" name=" {{data.talkmateId}}">
<span class="glyphicon glyphicon-ok-circle" id="ok-sign" aria-hidden="true"> </span>
</a>
<a href="#" title="{{_ "notifications.remove"}}" id="remove-btn" name="{{data.talkmateId}}">
<span class="glyphicon glyphicon-remove-circle" id="remove-sign" aria-hidden="true"> </span>
</a>
<a href="#" title="{{_ "notifications.block"}}" id="block-btn" name="{{data.talkmateId}}">
<span class="glyphicon glyphicon-remove-sign" id="block-sign" name="{{data.talkmateId}}" aria-hidden="true"> </span>
</a>
</div>
Meteor.Js
Template.navigation.events({
'click #block-btn': function(e, tmpl){
var friendList = Meteor.user().profile.friends;
var usrId = e.target.id;
var i = 0;
console.log(e.target.id);
console.log(friendList);
/*for(i = 0; i < friendList.length; i++){
if(friendList[i].id == usrId){
console.log(i);
friendList.splice(i, 1);
break;
}
}
console.log(friendList);
Meteor.users.update({_id: Meteor.userId()}, {
$set: {
'profile.friends': friendList
}});
Meteor.users.update({_id: Meteor.userId()}, {
$push: {
'profile.blocked': usrId
}
});*/
//Meteor.call('removeNotif', Meteor.user()._id, this.id);
}
});
问题是,无论我尝试什么,我都无法得到我想要的。 目标是,当我接受或阻止或删除某人时,我会更改 friend 状态,和/或将其从我的个人资料中删除和/或将其添加到阻止列表中。
但每次我都不能像e.target.id
那样打印的是跨度之一,而不是 <a></a>
之一。我尝试在 name 属性中传递用户 ID,但它不起作用,并且日志仅打印“未定义”。
我也尝试从 data- 属性获取它,但是每种访问它的方式都遇到问题(JQuery .data()
、HTML5 .dataset
或 vanilla JS .getAttribute("data-")
。
花了我一晚上的时间,找不到真正的解决方案。有人可以指导我吗?
谢谢你
最佳答案
您可以将 event.target
对象转换为 jQuery 对象,然后在其上使用选择器以使用 jQuery.parent()
获取其父对象。 ,像这样:
var $target = $(event.currentTarget);
var $parent = $target.parent(); // gets you the `a` tag as a jQuery object
var parentId = $parent.attr('id');
var parentTalkmate = $parent.attr('name')
您可以使用 this simple fiddle 来解决这个问题.
关于Javascript 目标属性未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30052387/