0

In my application, I have some tags that look like this

x Beer x Wine x Gummy Bears

If you click on the 'x' it's supposed to delete the tag.

The tags are created as you see below, with a link around the 'x'. The code inside the <%= %> is ruby. The parameterize method will, for example, make the Gummy Bears tag like '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>

I have JavaScript click events set up on the 'x' link. I am able to remove the 'x' immediately upon the click, but I can't get the actual tag name removed until a page refresh, which is not what I want. In order to get the tag.name removed immediately, I created a span class around the tag name that's the same as one of the html data attributes on the 'x' link. I saved the data attribute to a variable (this.span)

   this.spanVariable = $(r.target).attr("data-span");  #gets the tag.name parameterize from the data-span

For example, if it was the Gummy Bear tag that was clicked, this.spanVariable would now be 'Gummy-Bear'.

and then I would like to empty the html of the class 'Gummy-Bear', so I want to do something like this to evaluate the javascript variable so it becomes the class. I thought I could evaluate javascript inside of #{} but I guess not :(

   $('.#{this.spanVariable}').html('');

Is there a way to accomplish what I'm trying to do, basically make the variable evaluate so it can become the class that's also a jquery object (i.e. i can call jquery methods on).

4

2 に答える 2

1

Are you perhaps mixing server and client side? Try

$('.'+this.spanVariable).empty();
于 2013-03-27T06:37:02.563 に答える
1

Try this:

$('.' + this.spanVariable).remove();

This way should avoid race conditions, call some ajax, and do stuff when it returns:

$('.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...');
    }
  }
});
于 2013-03-27T06:37:48.613 に答える