Javascript href中的Contenteditable/jQuery符号和
我构建了一个在iframe中运行的小WYSIWYG编辑器。Javascript href中的Contenteditable/jQuery符号和,javascript,jquery,wysiwyg,Javascript,Jquery,Wysiwyg,我构建了一个在iframe中运行的小WYSIWYG编辑器。 我使用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实体&
我使用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客户机中是有效的行为-如果需要将所有链接返回到服务器而不使用HTML编码,我建议进行后期处理。最好的方法是使用相同的本地DOM编码,通过获取每个链接的href,将其粘贴到DOM节点中作为HTML,然后将其作为文本读回,从而发挥您的优势
在发送回服务器之前:
// 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();
} );
这似乎有点过度设计,但这是因为我使用了浏览器自己的可靠DOM读取/编码/解码API(与最初对HREF进行编码的API相同),并修改了DOM内容以便于Regexp,而不是尝试解析Regexp()中的href属性的危险路线
我在没有测试的情况下动态地写了这篇文章,但希望这些评论能够帮助您将其作为指南阅读,并将其应用到您的具体情况中
希望这能奏效 嘿@Barney,谢谢你精心安排的回答。我明天就去试试。另一方面:有没有办法让我知道哪些字符将被更改?我想你不必担心其他字符()-其他字符在上下文中往往是明确的-但最终这取决于浏览器,这就是为什么我建议使用浏览器自己的内部结构,而不是试图猜测它的内部工作。