内容可编辑/j在href中查询与符号

Contenteditable / jQuery ampersand in href

本文关键字:href 查询 符号 编辑      更新时间:2023-10-23

我构建了一个在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编码的符号。

两个问题:

  1. 有没有任何方法可以在不让浏览器将链接转换为html实体的情况下插入链接
  2. 如果这是不可能的,并且我必须在以后替换这些出现的字符,我还应该使用哪些字符

这是HTML客户端中的有效行为——如果您需要在没有HTML编码的情况下将所有链接返回到服务器,我建议您进行后期处理。最好的方法是使用相同的原生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内容以方便Regexp,而不是走上试图解析Regexp中href属性的危险路线(永远不要尝试用Regexp解析HTML!)。

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

希望这能奏效!