1

I have the following:

    link = {
        action: $link.attr('data-action') || '',
        dialogType: $link.attr('data-dialogType') || '',
        params: $link.attr('data-params') || '',
        title: $link.attr('title') || '',
        viewURL: $link.attr('data-href') || '',
        entity: $link.attr('data-entity') || '',
        row: $link.attr('data-row')
    };

I am just wondering. Is there a more clean way that I can do this or am I stuck with having to get the attributes like this.

  • 1
    If it wasn't for the inconsistency with `viewURL: $link.attr('data-href')` I would suggest something. – Wesley Murch Oct 08 '12 at 02:17
  • it is not good to get data using attr function, because if you set data with jquery, data(), it would not be in $.attr() – zb' Oct 08 '12 at 02:24

3 Answers3

3

Lots of functions you can pilfer for this: Get all Attributes from a HTML element with Javascript/jQuery

Or, just DRY it up:

var link = {};

['action', 'dialogType', 'params', 'title', 'href', 'entity', 'row'].forEach(function(i) {
    link[i] = $link.attr('data-' + i) || $link.attr(i);
});

Note that this requires changing viewURL to href. Also requires forEach support.

Community
  • 1
  • 1
glortho
  • 13,120
  • 8
  • 49
  • 45
1

simple use this

link=$link.data();
link.title=$link.attr('title');

edited as suggested by Wesley Murch

zb'
  • 8,071
  • 4
  • 41
  • 68
0

You could use the jQuery extend() method (for everything but title):

link = $.extend(link, $('a#mylink').data());
link.title = $('a#mylink').attr('title');

Here's a fiddle of it in action: http://jsfiddle.net/q4hqR/

pete
  • 24,141
  • 4
  • 37
  • 51
  • i would suggest to use `var $link=$('a#mylink');` to not make JQuery to parse dom each time; – zb' Oct 08 '12 at 02:36
  • Maybe it needs cached, maybe it doesn't. I'll leave that to the OP's discretion. – pete Oct 08 '12 at 02:38