简体   繁体   中英

jQuery - Data- attribute Quotes Issue

I'm working on a lightbox script and running into a problem using a custom data-lightbox attribute. What I'm trying to do is allow for the data-lightbox attribute settings to be added dynamically to the page - on an image.

Here's my image:

<a href="largeimage.png" data-lightbox='{"setting":"value","setting":"value"}'>
   <img src="thumbnail.png" />
</a>

Here's the part of the script that I'm using to inject the settings:

$('#testthumbnail').find('a').attr('data-lightbox',settings);

Settings is just a string, that is getting dumped into the attribute. When run, I don't receive any errors, and the settings are all injected to the data-lightbox attribute correctly. The settings aren't taking effect in the plugin though for 1 reason - somewhere along the lines the html that gets output to the page looks like this:

<a href="largeimage.png" data-lightbox="{"setting":value"}"> ...

The surrounding ' ' on the data-lightbox attribute are converted to " " - which won't work in my situation. Does anyone have any idea why the apostrophes are converted to quotes and how I can possibly get around this? Thanks!

UPDATE: I have the settings variable available both as a properly formatted JSON string as well as an object. I've tried using both the Object and the string inside the data-lightbox attribute, but am running into the same problem. The browser is converting my ' 's to " "s which is causing JSON errors.

Your quotes are wrong. HTML attributes need to use double quotes. So you need to use the single ones on the JSON value. The browser output you see is the browser trying to do the best it can to correct the html.

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