我构建了一个在 iframe 中运行的小型所见即所得编辑器。
我使用 jQuery 插入链接并设置其 href,如下所示:
$link.attr("href", url);
后来我获取了 iframe 的源代码并将其保存到 MySQL 数据库中。
我的问题:
当我插入带有&符号的链接时,例如http://www.example.org?foo=bar&bar=foo
浏览器将其转换为 http://www.example.org?foo=bar&bar=foo
.
然后,当我获取源代码时,链接包含 html 实体 &
而不是简单的 & 符号 &
。
旁注:我正在进一步处理链接,因此我实际上需要真正的链接,并且无法接受 html 编码的&符号。
两个问题:
- 有什么方法可以插入链接而不需要浏览器将其转换为 html 实体吗?
- 如果这是不可能的,并且我必须稍后替换这些出现的字符,那么我应该对哪些其他字符进行 html_decode?li>
最佳答案
这是 HTML 客户端中的有效行为 - 如果您需要在没有 HTML 编码的情况下将所有链接返回到服务器,我建议进行后处理。做到这一点的最佳方法是使用相同的 native DOM 编码,通过获取每个链接的 href,将其作为 HTML 粘贴到 DOM 节点,然后将其作为文本读回。
在发送回服务器之前:
// The string you'll send back to the server
var iframeContentString;
// The contents of the iframe as HTML
var $iframeContents = $iframe.find( 'body' ).clone();
// A list of all hrefs
var anchorHrefs = [];
// An empty node to use for HTML decoding using native methods
var $emptyNode = $( 'x' );
// For each link, decode the href and store
$iframeContents.find( 'a' ).each( function storeDecodedHref( element ){
// Assign the anchor's href to the empty node as HTML
$emptyNode.html( element.href );
// Store it as text
anchorHrefs.push( $emptyNode.text() );
// Replace the href with a string we can find with Regexp
element.href = '@REPLACED@';
} );
// Store the href-free content as a string
iframeContentString = $iframeContents.html();
// Replace our Regexp flag with the saved link
iframeContentString.replace( /href="@REPLACED@"/g, function injectDecodedHref(){
return anchorHrefs.unshift();
} );
这似乎有点过度设计,但那是因为我使用(jQuery 包装器)浏览器自己的可靠 DOM 读取/编码/解码 API - 与首先编码 href 的 API 相同 - 并修改然后,将 DOM 内容用于简单的正则表达式,而不是走上尝试解析正则表达式中的 href 属性的危险路线 ( never attempt to parse HTML with Regexp! )。
我在没有测试的情况下临时写了这篇文章,但希望这些评论可以帮助您将其作为指南阅读并将其应用于您的具体情况。
希望这有效!
关于javascript - href 中的 Contenteditable/jQuery 和符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198567/