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

发布于 2024-12-02 11:09:19 字数 1258 浏览 2 评论 0原文

我使用 jQuery 的 .data() 来处理自定义 HTML5 数据属性,其中属性的值需要能够包含单引号和双引号:

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

我知道使用像 " 可以使上述工作正常进行,但我无法始终控制值的输入方式。另外,我需要能够在标记中使用 HTML 标签,如下所示:

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

如果某种形式的 .replace() 是答案,那么需要在 < 读取值之前完成它code>.data()——也许可以将其应用到整个

WTF 这样的普通反斜杠转义也不起作用。

理想情况下,这可以灵活地与两者一起使用:

data-example="..."data-example='...'

但如果只有一种可能,那么我至少可以采用这种方式。有想法吗?

更新 - 更多背景信息:

我正在为 responsejs.com 处理此问题。实际应用可能是只为超过一定宽度的浏览器加载侧边栏(并在浏览器而不是 PHP 中处理此问题)。以 WordPress 为例,侧边栏可以包含小部件、图像等。PHP 标签内的引​​号不是问题,因为它们在到达浏览器之前会被解析为 HTML。例子:

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

        data-oweb=' 

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

        '
    >

    optional default markup for mobile and no-js browsers here

</aside>

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:

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

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

Normal backslash escaping like <abbr title="te\'st">WTF</abbr> doesn't work either.

Ideally this would have the flexibility to work w/ both:

data-example="..."
and
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:

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

        data-oweb=' 

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

        '
    >

    optional default markup for mobile and no-js browsers here

</aside>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

奢华的一滴泪 2024-12-09 11:09:19

没有办法解决这个问题,你必须正确转义这些值,否则 HTML 无法被正确解析。解析后你不能使用Javascript来纠正代码,因为那样它就已经失败了。

正确 HTML 编码的示例是:

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

您不能使用反斜杠来转义字符,因为它不是 Javascript 代码。您可以使用 HTML 实体来转义 HTML 代码中的字符。

如果您无法控制数据的输入方式,那么您就完蛋了。你只需要找到一种方法来控制它。

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.

Your example with proper HTML encoding would be:

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

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.

几度春秋 2024-12-09 11:09:19

使用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" />

Use encodeURI to escape quotation marks in your JSON object. Parse the string with 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" />

哭了丶谁疼 2024-12-09 11:09:19

当我使用 data 属性与 PHP 中的 html 元素一起传输一些数据时
对于 JavaScript,我只是在后端使用 base64_encode ,然后在客户端使用 base64Decode(input) 来获取数据。这样我就可以避免任何逃避狂欢的事情。
我使用的 JavaScript 代码位于此处 http://www.webtoolkit.info/

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/

猫七 2024-12-09 11:09:19

如果它们必须是带有 "' 之类的 HTML 字符串,为什么不为它们创建单独的 HTML 元素:http://jsfiddle.net/N7XXu/

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

与以下 JavaScript 结合:

$('.example').each(function() {
    var correspondingElem = $('.example-data[data-which="'
                              + $(this).data('which')
                              + '"]');
    $(this).data('example', correspondingElem.html());
});

alert($('.example').data('example'));

当然,隐藏 .example-data元素。

If they have to be HTML strings with " and ' and whatnot, why not just make separate HTML elements for them: http://jsfiddle.net/N7XXu/.

E.g. the 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:

$('.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.

开始看清了 2024-12-09 11:09:19

为了使其成为正确的 html,您必须转义麻烦的字符。我会用 HTML 实体来逃避它们。这意味着无论使用什么工具来输入这些信息都必须正确存储它们和/或在后端检索它们的工具必须转义它们。

然后,如果您想在 JS 中使用它们,则必须运行一些查找和替换函数来将字符转换回 HTML 和引号。

大多数后端开发语言都有某种“htmlescape/unescape”功能,因此这应该不难。

要通过 jQuery 取消转义,可以通过快速 Google 找到以下内容:

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.

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.

Most back-end dev languages have some sort of 'htmlescape/unescape' functionality, so that shouldn't be to hard.

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

季末如歌 2024-12-09 11:09:19

这是我创建的一个简单工具,您可以使用它来编码 html:

技巧是转义两次。

我添加了一个额外的 \n 替换来保留多行文本,因为它被 text() 丢弃。

此外,您需要转义引号以确保数据属性的安全。

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

这应该创建一个数据属性安全字符串。

您可以在这里测试它: http://jsfiddle.net/SplicePHP/n6HFq/

将其解码回来html 只需使用:

<script>
    var attr = $("#idOfElement").data('attribute');
    var decoded = $('<textarea/>').html(attr).val();
</script>

Here is a simple tool I created you can use to encode html:

The trick is to escape it twice.

I added an additional \n replace to preserve multiline text since it gets discarded by 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/

To decode it back to html simply use:

<script>
    var attr = $("#idOfElement").data('attribute');
    var decoded = $('<textarea/>').html(attr).val();
</script>
因为看清所以看轻 2024-12-09 11:09:19

您是否尝试过对数据使用单引号?

像这样:

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

have you tried using single quotes for your data?

Like this:

<p class="example" data-example='She said "WTF" on last night's show.'>
情丝乱 2024-12-09 11:09:19

正如这个答案所建议的那样,这是一个可能的解决方案:

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>

这里的关键是 :

wierdText = decodeURI(someText))

和 :

someText = encodeURI(wierdText)

是反向函数,可以保存您需要的任何字符串,而不会导致它被解释为 html 或 html 属性,因为它用于内联 href 标签,它是为了完成这项工作而设计的。

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.

往事风中埋 2024-12-09 11:09:19

这有点棘手,但您可以选择 dom 对象,其 data 属性包含单引号。诀窍是 \\'

<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

It is a little bit tricky but you can select dom objects with their data attributes that contains single quotes. 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

雨夜星沙 2024-12-09 11:09:19

如果您使用 Lodash,则可以使用 _.escape()_.unescape()。它将字符串中的字符“&”、“<”、“>”、“””和“'”转换为相应的 HTML 实体。

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

If you are using Lodash, then you can use _.escape() and _.unescape(). It converts the characters "&", "<", ">", '"', and "'" in string to their corresponding HTML entities.

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

∞琼窗梦回ˉ 2024-12-09 11:09:19

使用 btoa 方法设置数据并使用 atob 方法获取数据:

 $(document).data("test2",btoa('She said "<abbr title="What The F***">WTF<\/abbr>" on last nights show.">'))

或者简单地取消引用字符串作为变量:

 var stringer = 'She said "<abbr title="What The F***">WTF<\/abbr>" on last nights show.">'

 $(document).data("test2",stringer);

References

Use the btoa method to set the data and the atob method to get it:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文