【问题标题】:Contenteditable / jQuery ampersand in hrefContenteditable / jQuery & 符号在href
【发布时间】:2013-11-25 16:48:37
【问题描述】:

我构建了一个在 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 哪些其他字符?

【问题讨论】:

    标签: javascript jquery wysiwyg


    【解决方案1】:

    这是 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 (never attempt to parse HTML with Regexp!) 中的 href 属性的危险路线。

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

    希望这行得通!

    【讨论】:

    • 嘿@Barney,感谢您精心布置的答案。我明天试试。附带说明:有什么方法可以找出哪些字符将被更改?
    • 我认为你不需要担心其他字符 (there's some talk on this here) — 其他字符在上下文中往往是明确的 — 但归根结底这取决于浏览器,这就是为什么我建议使用浏览器自己的内部结构而不是试图猜测它的内部工作原理。
    猜你喜欢
    • 2010-11-07
    • 2014-01-29
    • 2011-10-12
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多