最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding a data attribute(with special characters) to a dom element using jquery - Stack Overflow

programmeradmin0浏览0评论

I am trying to add a data attribute to a html element. The data attribute(data-description) can contain special characters like apostrope.

InsertHtml = InsertHtml + '<tr id="DashboardRow0" data-description=\'' + JSON.stringify(data[0])+ '\'><td>' + </td></tr>';
htmlElement.append(InsertHtml);

The code to access this data is given below...

var $row = $("#DashboardRow0");
var jsonData = eval('(' + $row.attr('data-description') + ')');

But the problem is...If there is a single apostrophe within JSON.stringify(data[0]) data..the browser replaces it with a " effectively terminating the string.

Is there any know solution to adding data attributes with special characters to nodes?

I am trying to add a data attribute to a html element. The data attribute(data-description) can contain special characters like apostrope.

InsertHtml = InsertHtml + '<tr id="DashboardRow0" data-description=\'' + JSON.stringify(data[0])+ '\'><td>' + </td></tr>';
htmlElement.append(InsertHtml);

The code to access this data is given below...

var $row = $("#DashboardRow0");
var jsonData = eval('(' + $row.attr('data-description') + ')');

But the problem is...If there is a single apostrophe within JSON.stringify(data[0]) data..the browser replaces it with a " effectively terminating the string.

Is there any know solution to adding data attributes with special characters to nodes?

Share Improve this question asked Nov 24, 2010 at 7:48 WhimsicalWhimsical 6,3552 gold badges34 silver badges40 bronze badges 2
  • 2 That eval hurts my eyes. – Gabi Purcaru Commented Nov 24, 2010 at 7:49
  • try to avoid eval if possible , did you try jquery.metada plugin if it has any options. – kobe Commented Nov 24, 2010 at 7:51
Add a ment  | 

3 Answers 3

Reset to default 7

try to escape data before stringify

data[0].myProblemField = escape(data[0].myProblemField)
JSON.stringify(data[0])

<edit>
or better

 for(var prop in data[0]) if(typeof(data[0][prop]) == "string") 
   data[0][prop] = escape(data[0][prop]);

</edit>

and afterwards

var jsonData = eval('(' + $row.attr('data-description') + ')');
jsonData.myProblemField = unescape(data[0].myProblemField)

Not entirely sure whether this'll help you (i.e. whether this is all happening in the same document), but have you considered using jQuery's .data()? It won't have these problems, as the data is stored as a variable.

If you write in html

<tr id="some &quot; "><td>...</td></tr>

You get

<tr id="some " "><td>...</td></tr>

in browser.

发布评论

评论列表(0)

  1. 暂无评论