简体   繁体   中英

How to add single quotes around the data-setup value that contains a JSON string that must use double quotes?

I have the following code that creates elements and I can even add more attributes, classes, id among others

    if(is_video){
        Mcontent = $(document.createElement("video"))
        Msource = $(document.createElement("source"))
        Msource.attr("src",url)
        Msource.attr("type","video/"+formato)
        Mcontent.attr("class","video-js vjs-default-skin")
        Mcontent.append(Msource)
    }

Using the following code, I add attributes to a specific tag:

 var json = {"aspectRatio":"640:267", "playbackRates": [1, 1.5, 2]}; const content = $('video').addClass('video-js vjs-default-skin') content.attr('data-setup', JSON.stringify(json));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <video></video>

This gives me the following result when I inspect the code with the browser's developer tool:

<video class="video-js vjs-default-skin" data-setup="{"aspectRatio":"640:267","playbackRates":[1,1.5,2]}">

</video>

I need the attribute data-setup='' this with single quotes and not with double quotes data-setup="" , how can I get this result:

<video class="video-js" data-setup='{"aspectRatio":"640:267","playbackRates":[1,1.5,2]}'>

</video>

Observe the note of the official documentation videoJS . which warns: Note: You must use single-quotes around the value of data-setup as it contains a JSON string which must use double quotes.

You don't need to pollute your HTML with single-quotes. JavaScript will encode the attribute value correctly for you....

 const Mcontent = $('video').addClass('video-js vjs-default-skin') Mcontent.attr('data-setup', JSON.stringify({ aspectRatio: "640:267", playbackRates: [1, 1.5, 2] })) // this is what the generated HTML will look like $('pre').text($('section').html()) // decode example, just showing that it's possible console.info(JSON.parse($('video').attr('data-setup')))
 section { display: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <section> <video></video> </section> <pre></pre>

The HTML-encoded value, ie

<video data-setup="{&quot;aspectRatio&quot;:&quot;640:267&quot;,&quot;playbackRates&quot;:[1,1.5,2]}">

will be perfectly readable as JSON (assuming that's what is used for).

Here's an example of the generated markup ~ JSFiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM