在属性中存储 HTML

Storing HTML Within Attribute

我正在像这样在元素属性中存储 HTML 代码。

<div data-html-code="<iframe width="560" height="315" src="https://www.youtube.com/embed/sNhhvQGsMEc" frameborder="0" allowfullscreen></iframe>"></div>

如何使用 jQuery/Javascript 转义所有必要的字符以使其有效?

使用这个htmlEscape方法

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

这应该会为您提供一个可用作有效 html 属性值的字符串