Domanda

I've run into a problem with a plugin I'm working on. I'm allowing users to pass some text to the plugin like so:

data-plugin='{ "setting" : "hello world" }'

no problems there, until a special character is introduced:

data-plugin='{ "setting" : "hello world, it's been awhile." }'

The apostrophe just halts everything and doesn't throw any errors. I'm not sure how I would go about allowing users to type this as they normally would?

EDIT: Here's the exact attribute that is causing the problem:

data-plugin='{
   "foreground":"1_foreground.png", 
   "horizon":"50,120",
   "subtitle":"Hello world. It's been awhile.",
   "subtitle_speed":"3500,2000",
   "subtitle_color":"#ff5b00",
   "subtitle_pos":"bottom"
}'

EDIT 2:

When \' is used in the setting, this is logged before merging objects inside the plugin:

{
       "foreground":"1_foreground.png", 
       "horizon":"50,120",
       "subtitle":"Hello world. \

Directly after that I'm using $.extend to merge this then apply it as data.

THIS IS HOW IT IS SETUP:

Call a plugin on a ton of elements:

$('.el').plugin({ "setting1" : "value" });

Modify those settings by using them here:

<div class="el"></div>
<div class="el" data-plugin='{ "setting1" : "special value" }'></div>

Anyways, that isn't the issue. The issue is trying to plug an apostrophe into the value. Single quotes on any HTML element is valid.

Thanks!

È stato utile?

Soluzione

data-plugin='{ "setting" : "hello world, it's been awhile." }'

Since you're wrapping your JSON string with apostrophes, you need to escape apostrophes inside of your string.

Change it to:

data-plugin='{ "setting" : "hello world, it\'s been awhile." }'

EDIT: Ok I think I have an idea what you're trying to do based on data-plugin being an html attribute:

I tried a JSFIDDLE to reproduce and here's what I get:

<input type='hidden' data-plugin='{
   "foreground":"1_foreground.png", 
   "horizon":"50,120",
   "subtitle":"Hello world. It\'s been awhile.",
   "subtitle_speed":"3500,2000",
   "subtitle_color":"#ff5b00",
   "subtitle_pos":"bottom"
}'>

and javascript

alert($('input').data('plugin'));

and it causes the error you noted in your question.

Per the first comment on your question, I escaped the apostrophe to &apos; and when I run

alert($('input').data('plugin'));

and I get a proper response. This will alert to a JSON object, so

alert($('input').data('plugin').foreground);

alerts "1_foreground.png". To turn it back into JSON if that's what you're trying to do you need to:

var jsonPluginSettings = JSON.stringify($('input').data('plugin'));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top