简体   繁体   English

试图删除数据值等于先前创建的变量的元素?

[英]Trying to remove an element with data-value equal to a previously created variable?

When I click on a "trash" button I want to delete the message block.当我单击“垃圾箱”按钮时,我想删除消息块。 There are multiple message blocks but they all have unique data-values .有多个消息块,但它们都有唯一的data-values The id of the targeted block I want to delete is stored in the data-value of .send-message-button .我要删除的目标块的id存储在.send-message-buttondata-value中。

I tried making a variable that I could pass onto the targeted .messageblock element.我尝试制作一个可以传递给目标.messageblock元素的变量。 I checked with an alert to see if the variable gets the proper number, which it does.我检查了一个alert ,看看变量是否得到了正确的数字,它确实如此。 However when I alert the whole thing, it gives [object object] (without the .remove , of course).但是,当我alert整个事情时,它会给出[object object] (当然没有.remove )。

How can I do this?我怎样才能做到这一点?

var trashid = $(".send-message-button").attr("data-value");
$('.message-block').attr("data-value", trashid).remove();

If you want to retrieve an element using the value of one of its attributes you need to use the attribute selector, not the setter of the attr() method.如果要使用其属性之一的值检索元素,则需要使用属性选择器,而不是attr()方法的设置器。

There's two main ways to do this.有两种主要方法可以做到这一点。 Firstly if the data attribute is present in the DOM then you can use an attribute selector:首先,如果data属性存在于 DOM 中,那么您可以使用属性选择器:

var trashid = $(".send-message-button").data('value');
$('.message-block[data-value="' + trashid + '"]').remove();

Alternatively if the data attribute is held in jQuery's cache (as will be the case if you use data() as a getter/setter, as you should be) then you can use filter() instead:或者,如果data属性保存在 jQuery 的缓存中(如果您使用data()作为 getter/setter,则应该如此),那么您可以使用filter()代替:

var trashid = $(".send-message-button").data('value');
$('.message-block').filter((i, e) => $(e).data('value') === trashid).remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM