Storing HTML Within Attribute

為{幸葍}努か 提交于 2019-12-02 10:09:38

问题


I'm storing HTML code within an element attribute like so.

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

How can I escape all the necessary characters to make this valid using jQuery/Javascript?


回答1:


use this htmlEscape method

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

this should give you a string that can be used as a valid html attribute value



来源:https://stackoverflow.com/questions/35299146/storing-html-within-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!