在我的应用程序中,我有一些看起来像这样的标签
x Beer
x Wine
x Gummy Bears
如果点击'x',它应该删除标签。
如下所示创建标签,并在“x”周围添加链接。 <%=%>内的代码是红宝石。例如,参数化方法将使Gummy Bears标记像'Gummy-bears'。
<a href="#" class="link tag" data-span="<%= tag.name.parameterize %>"data-question="<%= @question.id %>" data-tag="<%= tag.name%>" >x</a>
<span class="<%= tag.name.parameterize %>"><%= tag.name %></span>
我在'x'链接上设置了JavaScript点击事件。我可以在点击后立即删除'x',但是在页面刷新之前我无法删除实际的标签名称,这不是我想要的。为了立即删除tag.name,我在标记名称周围创建了一个span类,它与'x'链接上的一个html数据属性相同。我将data属性保存到变量(this.span)
this.spanVariable = $(r.target).attr("data-span"); #gets the tag.name parameterize from the data-span
例如,如果是点击的Gummy Bear标签,this.spanVariable现在将是'Gummy-Bear'。
然后我想清空类'Gummy-Bear'的html,所以我想做这样的事情来评估javascript变量,使它成为类。我以为我可以评估#{}内部的javascript,但我猜不是:(
$('.#{this.spanVariable}').html('');
有没有办法完成我正在尝试做的事情,基本上让变量进行评估,这样它就可以成为也是jquery对象的类(即我可以调用jquery方法)。
答案 0 :(得分:1)
您是混合服务器端还是客户端? 尝试
$('.'+this.spanVariable).empty();
答案 1 :(得分:1)
试试这个:
$('.' + this.spanVariable).remove();
这种方式应该避免竞争条件,调用一些ajax,并在返回时执行操作:
$('.xclass').click(function(e) {
var spanVariable = $(this).data("span");
$.ajax("/my/server/endpoint?tag=" + spanVariable, {
dataType: 'json',
success: function(result) {
$('.' + result.spanVariable).remove();
$('.tag[data-span=' + result.spanVariable + ']').remove();
},
error: function() {
console.log('Couldn't remove the tag...');
}
}
});