简体   繁体   English

使用 Javascript 的 HTML5 数据属性中的转义引号

[英]Escape Quotes In HTML5 Data Attribute Using Javascript

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 &quot;我知道使用像&quot;这样的字符代码。 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:另外,我需要能够在标记中使用 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>这样的普通反斜杠 escaping 也不起作用。

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 .我正在为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).一个实际的应用可能是只为超过一定宽度的浏览器加载侧边栏(并在浏览器而不是 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.例如,在 WordPress 的情况下,侧边栏可以包含小部件、图像等。PHP 标签中的引号是非问题 b/c,它们在进入浏览器之前被解析为 Z4C4AD5FCA2E7A3AAF74DBB1CED00381。 Example:例子:

<aside id="primary" class="sidebar" 

        data-oweb=' 

            <?php dynamic_sidebar( 'primary' ); ?>

        '
    >

    optional default markup for mobile and no-js browsers here

</aside>

There is no way around it, you have to escape the values properly, or the HTML can't be parsed properly.没有办法绕过它,您必须正确转义值,否则无法正确解析 HTML。 You can't use Javascript to correct the code after it is parsed, because then it has already failed.您不能在解析代码后使用 Javascript 来更正代码,因为它已经失败了。

Your example with proper HTML encoding would be:您使用正确 HTML 编码的示例将是:

<p class="example" data-example="She said &quot;&lt;abbr title=&quot;What The F***&quot;&gt;WTF&lt;/abbr&gt;&quot; on last night's show.">

You can't use backslash to escape characters, because it's not Javascript code.您不能使用反斜杠来转义字符,因为它不是 Javascript 代码。 You use HTML entities to escape characters in HTML code.您使用 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.你只需要找到一种方法来控制它。

Use encodeURI to escape quotation marks in your JSON object.使用 encodeURI 转义 JSON 对象中的引号。 Parse the string with decodeURI.使用 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" />

If they have to be HTML strings with " and ' and whatnot, why not just make separate HTML elements for them: http://jsfiddle.net/N7XXu/ .如果它们必须是带有"'之类的 HTML 字符串,为什么不为它们制作单独的 HTML 元素:http: //jsfiddle.net/N7XXu/

Eg 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元素。

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, '&quot;'));
    });            
</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>

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.当我使用 data 属性将一些数据与 html 元素一起从 PHP 传输到 JavaScript 时,我只在后端使用base64_encode ,然后在客户端使用base64Decode(input)来取回数据。 This way I avoid any and all escaping orgy.这样我就避免了任何逃避狂欢。 The JavasScript code I use is located here http://www.webtoolkit.info/我使用的 JavaScript 代码位于http://www.webtoolkit.info/

For it to be proper html, you have to escape the troublesome characters.为了使它成为正确的 html,您必须转义麻烦的字符。 I'd escape them with HTML entities.我会用 HTML 实体转义它们。 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.这意味着用于输入此信息的任何工具都必须正确存储它们和/或在后端检索它们的工具必须转义它们。

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 取消转义,可以通过快速 Google 找到以下内容:http: //www.naveen.com.au/javascript/jquery/encode-or-decode-html-entities-with-jquery/289

New to Stack Overflow so I don't have enough rep points to vote, but I wanted to clarify the solution as I misinterpreted the accepted answer by @Guffa that I was screwed. Stack Overflow的新功能因此我没有足够的重复点来投票,但我想澄清解决方案,因为我误解了@Guffa接受的答案,我被搞砸了。

I had a similar question regarding escape/special characters in HTML5 data-attributes. 关于HTML5数据属性中的转义/特殊字符我有类似的问题。 The question/solution: Escape/Special Characters from user input to HTML5 data-attributes using URL Encode/Decode 问题/解决方案: 使用URL Encode / Decode从用户输入转换为HTML5数据属性的转义/特殊字符

Dan Smith provided the solution I used with encodeURI()/decodeURI(). Dan Smith提供了我使用encodeURI()/ decodeURI()的解决方案。 However, I dismissed it initially because it was so far down with only 1 rep points. 但是,我最初驳回了它,因为它只有1个重复点。

Any answers with manually escaping the characters become messy and time-consuming. 手动转义字符的任何答案都会变得混乱和耗时。

Any answers with escape() method are now deprecated. 现在不推荐使用escape()方法的任何答案。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape

I like to store data in javascript directly. 我喜欢直接在javascript中存储数据。 Instead of this: 而不是这个:

<p class="example" data-oweb="<?=str_replace('\'', '\\\'', $var)?>">Content</p>
<script>
  var example = $('.example').data("example");
  DoSomething(example);
</script>

Do this: 做这个:

<p class="example">Content</p>
<script>
  var example = '<?=str_replace('\'', '\\\'', $var)?>';
  DoSomething(example); 
</script>

Or if the usage is in a remote script you control, store the value(s) in a global: 或者,如果用法位于您控制的远程脚本中,则将值存储在全局中:

<p class="example">Content</p>
<script>
  window.MyDataValues={};
  window.MyDataValues.Example = '<?=str_replace('\'', '\\\'', $var)?>';
</script>

Or if you can't control the remote script, and the info has to be stored as a data attribute you can set it with javascript after you figure out a way to target the paragraph: 或者,如果您无法控制远程脚本,并且必须将信息存储为数据属性,则可以在找到定位段落的方法后使用javascript进行设置:

<p id="example" data-oweb>Content</p>
<script>
    document.getElementById("example");
    element.dataset.oweb = '<?=str_replace('\'', '\\\'', $var)?>';
</script>

It is a little bit tricky but you can select dom objects with their data attributes that contains single quotes.这有点棘手,但您可以选择具有包含单引号的data属性的 dom 对象。 The trick is \\'诀窍是\\'

<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>

Fiddle小提琴

have you tried using single quotes for your data?您是否尝试过对数据使用单引号?

Like this:像这样:

<p class="example" data-example='She said "WTF" on last night's show.'>

As this answer suggestest, here is a possible solution:正如这个答案所暗示的,这是一个可能的解决方案:

 var popup = $('#placeholder'); popup.html(` <div data-message="${encodeURI("i could be what ever you need \' \" i will escape; ")}" > </div> `). console.log(decodeURI(popup.find('div');data("message")));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="placeholder"> </div>

The key here is that:这里的关键是:

wierdText = decodeURI(someText))

and:和:

someText = encodeURI(wierdText)

are reverse functions and can hold what ever string you need without causing it to be interpreted as html nor html attribut because it's used in inline href tag, it was made to do this job.是反向函数,可以保存您需要的任何字符串,而不会导致它被解释为 html 或 html 属性,因为它用于内联 href 标记,它是用来完成这项工作的。

If you are using Lodash, then you can use _.escape() and _.unescape() .如果你使用 Lodash,那么你可以使用_.escape()_.unescape() It converts the characters "&", "<", ">", '"', and "'" in string to their corresponding HTML entities.它将字符串中的字符 "&"、"<"、">"、'"' 和 "'" 转换为它们对应的 HTML 实体。

Reference : https://lodash.com/docs/#escape参考: https ://lodash.com/docs/#escape

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参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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