使用 Javascript 在 HTML5 数据属性中转义引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7260195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escape Quotes In HTML5 Data Attribute Using Javascript
提问by ryanve
I'm using jQuery's .data()
to work with custom HTML5 data attributes where the value of the attribute needs to be able to contain both single quotes and double quotes:
我正在使用 jQuery.data()
来处理自定义 HTML5 数据属性,其中属性的值需要能够同时包含单引号和双引号:
<p class="example" data-example="She said "WTF" on last night's show.">
I know using character codes like "
in the data attribute value could make the above work, but I can't always control how the values are inputted. Plus, I need to be able to use HTML tags in the markup, like this:
我知道"
在 data 属性值中使用字符代码可以使上述工作,但我不能总是控制如何输入值。另外,我需要能够在标记中使用 HTML 标签,如下所示:
<p class="example" data-example="
She said "<abbr title="What The F***">WTF</abbr>" on last night's show.
">
If some form of .replace()
is the answer, then it needs to be done before the value is read by .data()
—maybe by applying it across the entire <body>
?
如果.replace()
答案是某种形式的,那么需要在读取值之前完成.data()
它——也许通过将它应用于整个<body>
?
Normal backslash escaping like <abbr title="te\'st">WTF</abbr>
doesn't work either.
正常的反斜杠转义<abbr title="te\'st">WTF</abbr>
也不起作用。
Ideally this would have the flexibility to work w/ both:
理想情况下,这将具有与两者一起工作的灵活性:
data-example="..."
and
data-example='...'
data-example="..."
和
data-example='...'
But if it's only possible one way then I could at least roll with that. Ideas?
但如果只有一种可能,那么我至少可以接受。想法?
Update- some more context:
更新- 一些更多的背景:
I'm working on this for responsejs.com. An actual application of this might be to only load a sidebar for browsers above a certain width (and have this handled in the browser rather than PHP). In the case of WordPress for example, the sidebar could contain widgets, images, etc. The quotes within PHP tags are a non-issue b/c they are parsed into HTML before they get to the browser. Example:
我正在为responsejs.com处理这个问题。这个的实际应用可能是只为超过特定宽度的浏览器加载侧边栏(并在浏览器而不是 PHP 中处理)。例如,在 WordPress 的情况下,侧边栏可能包含小部件、图像等。 PHP 标记中的引号是非问题 b/c,它们在到达浏览器之前被解析为 HTML。例子:
<aside id="primary" class="sidebar"
data-oweb='
<?php dynamic_sidebar( 'primary' ); ?>
'
>
optional default markup for mobile and no-js browsers here
</aside>
回答by Guffa
There is no way around it, you have to escape the values properly, or the HTML can't be parsed properly. You can't use Javascript to correct the code after it is parsed, because then it has already failed.
没有办法解决它,您必须正确转义值,否则无法正确解析 HTML。您不能在解析后使用 Javascript 来更正代码,因为它已经失败了。
Your example with proper HTML encoding would be:
您使用正确 HTML 编码的示例是:
<p class="example" data-example="She said "<abbr title="What The F***">WTF</abbr>" on last night's show.">
You can't use backslash to escape characters, because it's not Javascript code. You use HTML entities to escape characters in HTML code.
您不能使用反斜杠来转义字符,因为它不是 Javascript 代码。您可以使用 HTML 实体来转义 HTML 代码中的字符。
If you can't control how the data is input, then you are screwed. You simply have to find a way to take control over it.
如果您无法控制数据的输入方式,那么您就完蛋了。你只需要找到一种方法来控制它。
回答by Dan Smith
Use encodeURI to escape quotation marks in your JSON object. Parse the string with decodeURI.
使用 encodeURI 来转义 JSON 对象中的引号。使用 decodeURI 解析字符串。
var popup = document.getElementById('popup'),
msgObj = JSON.parse(decodeURI(popup.dataset.message));
console.log(msgObj);
<a id="popup" href="#" data-message="%7B%22title%22:%22Print%22,%22message%22:%22Printing%20not%20yet%20implemented%22%7D" />
回答by pimvdb
If they have to be HTML strings with "
and '
and whatnot, why not just make separate HTML elements for them: http://jsfiddle.net/N7XXu/.
如果它们必须是带有"
and'
和诸如此类的HTML 字符串,为什么不为它们制作单独的 HTML 元素:http: //jsfiddle.net/N7XXu/。
E.g. the HTML:
例如 HTML:
<p class="example" data-which="1">a</p>
<p class="example-data" data-which="1">She said "<abbr title="What The F***">WTF</abbr>" on last night's show.</p>
in combination with the following JavaScript:
结合以下 JavaScript:
$('.example').each(function() {
var correspondingElem = $('.example-data[data-which="'
+ $(this).data('which')
+ '"]');
$(this).data('example', correspondingElem.html());
});
alert($('.example').data('example'));
Of course, hide the .example-data
elements.
当然,隐藏.example-data
元素。
回答by Dieter Gribnitz
Here is a simple tool I created you can use to encode html:
这是我创建的一个简单工具,可用于对 html 进行编码:
The trick is to escape it twice.
诀窍是逃避它两次。
I added an additional \n replace to preserve multiline text since it gets discarded by text().
我添加了一个额外的 \n 替换来保留多行文本,因为它被 text() 丢弃。
In addition you need to escape the quotes to make it safe for a data attribute.
此外,您需要对引号进行转义以使其对数据属性安全。
<div id="esc"></div>
<textarea id="escinput" placeholder="Enter text"></textarea>
<script>
$("#escinput").bind("change paste keyup", function(){
$("#esc").text($(this).val().replace(/\n/g,'\n'));
$("#esc").text($("#esc").html().replace(/"/g, '"'));
});
</script>
This should create a data attribute safe string.
这应该创建一个数据属性安全字符串。
You can test it here: http://jsfiddle.net/SplicePHP/n6HFq/
你可以在这里测试:http: //jsfiddle.net/SplicePHP/n6HFq/
To decode it back to html simply use:
要将其解码回 html,只需使用:
<script>
var attr = $("#idOfElement").data('attribute');
var decoded = $('<textarea/>').html(attr).val();
</script>
回答by DA.
For it to be proper html, you have to escape the troublesome characters. I'd escape them with HTML entities. This means that whatever tool is being used to input this information would have have to store them properly and/or the tool retrieving them on the back end would have to escape them.
要使其成为正确的 html,您必须转义麻烦的字符。我会用 HTML 实体来逃避它们。这意味着任何用于输入此信息的工具都必须正确存储它们和/或在后端检索它们的工具必须逃避它们。
Then if you want to use them in your JS, you'd have to run some find-and-replace functions to convert the characters back into HTML and quotes.
然后如果你想在你的 JS 中使用它们,你必须运行一些查找和替换函数来将字符转换回 HTML 和引号。
Most back-end dev languages have some sort of 'htmlescape/unescape' functionality, so that shouldn't be to hard.
大多数后端开发语言都有某种“htmlescape/unescape”功能,所以这应该不难。
To unescape it via jQuery, here's something found via a quick Google: http://www.naveen.com.au/javascript/jquery/encode-or-decode-html-entities-with-jquery/289
要通过 jQuery 对其进行转义,这里有一些通过快速谷歌找到的内容:http: //www.naveen.com.au/javascript/jquery/encode-or-decode-html-entities-with-jquery/289
回答by DA.
As I use the data attribute to transport some data together with the html element from PHP
to the JavaScript, I just use base64_encode
on the backend , then on the client side use base64Decode(input)
to get the data back. This way I avoid any and all escaping orgy.
The JavasScript code I use is located here http://www.webtoolkit.info/
当我使用 data 属性将一些数据与 html 元素一起从 PHP 传输到 JavaScript 时,我只是base64_encode
在后端使用,然后在客户端使用 base64Decode(input)
来取回数据。这样我就可以避免任何和所有逃避的狂欢。我使用的 JavaScript 代码位于http://www.webtoolkit.info/
回答by fozuse
It is a little bit tricky but you can select dom objects with their data
attributes that contains single quotes. The trick is \\'
这有点棘手,但您可以选择具有data
包含单引号的属性的dom 对象。诀窍是\\'
<div id="text" data-message="Stanley Kubrick's Oranges">Hello</div>
<script>
var message = "Stanley Kubrick\'s Oranges";
$("#text[data-message='"+message+"']").fadeOut("slow");
</script>
回答by rajesh kumar
If you are using Lodash, then you can use _.escape()
and _.unescape()
. It converts the characters "&", "<", ">", '"', and "'" in string to their corresponding HTML entities.
如果您使用的是 Lodash,那么您可以使用_.escape()
和_.unescape()
。它将字符串中的字符 "&"、"<"、">"、'"' 和 "'" 转换为其对应的 HTML 实体。
Reference : https://lodash.com/docs/#escape
回答by Paul Sweatte
Use the btoa
method to set the data and the atob
method to get it:
使用btoa
设置数据的atob
方法和获取数据的方法:
$(document).data("test2",btoa('She said "<abbr title="What The F***">WTF<\/abbr>" on last nights show.">'))
Or simply dereference the string as a variable:
或者简单地将字符串取消引用为变量:
var stringer = 'She said "<abbr title="What The F***">WTF<\/abbr>" on last nights show.">'
$(document).data("test2",stringer);
References
参考