【问题标题】:Why does retrieving html from inside a NOSCRIPT return htmlentities?为什么从 NOSCRIPT 中检索 html 会返回 htmlentities?
【发布时间】:2010-10-24 02:43:22
【问题描述】:

考虑代码:

<noscript><div>FOO</div></noscript>

跑步

$('noscript').html();

返回&amp;lt;div&amp;gt;FOO&amp;lt;/div&amp;gt;

但正在运行

$('noscript').text();

返回原始 html。

这与我的预期相反。有对此的解释吗?

【问题讨论】:

  • 据我记忆,使用 text() 永远不会返回 HTML 标签。

标签: jquery


【解决方案1】:

似乎存在一个 PhantomJS 错误,它似乎逃脱了 page.content 中 noscript 标记中的实体。此功能将使它们恢复到应有的形式。 S object 来自 npmjs.org 上的字符串包。

function fixNoScript(content) {
  var noscript = /<\s*noscript\s*>([^<]+)<\s*\/\s*noscript\s*>/ig;
  var matches = content.match(noscript);
  for ( var i = 0; match && i < matches.length; i++ ) {
    var decoded = S(matches[i]).decodeHTMLEntities().s;
    var index = content.indexOf(matches[i]);
    content = content.substring(0, index) + 
              decoded +
              content.substring(index + matches[i].length);

  }
  return content;
}

【讨论】:

  • 我不确定我是否提倡使用正则表达式来解决这个问题。在我看来,像 Cheerio 这样好的 HTML Parser 可能是更好的选择。
【解决方案2】:

这更像是 DOM 的怪癖而不是 jQuery 的怪癖:

$("<noscript><div>FOO</div></noscript>")[0].innerHTML == "&lt;div&gt;FOO&lt;/div&gt;"

$("<noscript><div>FOO</div></noscript>")[0].textContent == "<div>FOO</div>"

正如this answer 所解释的,基本上,此操作的行为并不一致。

【讨论】:

    【解决方案3】:

    是的,这是完全不一致的,因为 htmlentities 被破坏了。 &copy 在 BOTH 函数中总是转换为版权字符。基本上应该有一个函数可以直接提取 html,而不进行任何转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 2013-06-05
      相关资源
      最近更新 更多