href中的contenteditable / jQuery&符号

时间:2013-11-25 16:48:38

标签: 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实体&而不是简单的&符号&

旁注:我正在进一步处理链接,所以我实际上需要真正的链接,不能接受html编码的&符号。

两个问题:

  1. 有没有办法在没有浏览器将其转换为html实体的情况下插入链接?
  2. 如果那是不可能的,我必须在以后更换那些其他字符应该html_decode吗?

1 个答案:

答案 0 :(得分:2)

这是HTML客户端中的有效行为 - 如果您需要在没有HTML编码的情况下将所有链接恢复到服务器,我建议进行后期处理。最好的方法是通过获取每个链接的href,以HTML格式粘贴到DOM节点并将其作为文本读回来使用相同的本机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 - 与首先编码hrefs的相同 - 并且修改那么容易使用Regexp的DOM内容,而不是试图解析Regexp(never attempt to parse HTML with Regexp!)中的href属性的危险路径。

我在没有测试的情况下即时编写了这篇文章,但希望这些评论可以帮助您将其作为指南阅读并将其应用于您的具体情况。

希望这有效!

相关问题