Ross Anderson
Ross Anderson

Reputation: 83

split data-string containing options

I've implemented sharing buttons on to my site which passes the separate components from the data attributes (in the example below) together for each social site.

html

<span data-title="Stackoverflow" data-description="Website" data-media="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a" data-url="url":"https://stackoverflow.com/questions/" class="share">     

script

var base = $('.share'),
    thisUrl = window.location.href,
    thistitle = base.data('title'),
    thisdescription = base.data('description'),
    thismedia = base.data('media');

What I would prefer to do, would be to have just one data string like the span I put together below containing all the options which I could then split and pass on to:

title = options.title

description = options.description

media = options.media

url = options.url

HTML:

<span data-opt="{"options":{"title":"Stackoverflow","description":"Website","media":"https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a","url":"https://stackoverflow.com/questions/"}}" >     

Any help with pointing me in the right direction or any advice would be greatly appreciated.

Upvotes: 0

Views: 41

Answers (1)

charlietfl
charlietfl

Reputation: 171689

Change the outer attribute value quotes to single ones and get the whole object using jQuery data().

So long as the string is valid json , data() will automatically parse it to object/array

var data = $('span[data-opt]').data('opt');
console.log('Title is', data.options.title);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span data-opt='{"options":{"title":"Stackoverflow","description":"Website","media":"https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a","url":"https://stackoverflow.com/questions/"}}' >

Upvotes: 3

Related Questions