views:

249

answers:

1

I've written some jQuery for parsing an id out of a link's href. It works, but I'm wondering if there's a cleaner, more idiomatic jQuery way of doing it:

<a class="edit_tags" href="/image/edit_tags/id/2">Edit Tags</a>

<script type="text/javascript" charset="utf-8">
  $('.edit_tags').click(function(event) {
    event.preventDefault();
    var tagged_item = $(this);
    var tagged_item_href = $(tagged_item).attr('href');
    var result = tagged_item_href.match(/\/id\/(\d+)/);
    var tagged_item_id = result[1];
    alert('Editing Tags for '+tagged_item_id);
  })
</script>

I'm still at the noob stage of jQuery/javascript, and am keen to find the shortcuts... ;-)

A: 

About the two first variables, it's not necessary to make other jQuery object only to get an attribute value, you can do that in one step, you can also apply the regex and access to the first match in one step:

$('.edit_tags').click(function(event) {
  event.preventDefault();
  var tagged_item_id = $(this).attr('href').match(/\/id\/(\d+)/)[1];
  alert('Editing Tags for '+tagged_item_id);
})
CMS
Exactly what I was after! I'll get there yet...
Dycey