简体   繁体   English

在Javascript中附加HTML

[英]Appending html in Javascript

I'm trying to edit a Wordpress plugin that uses JavaScript. 我正在尝试编辑使用JavaScript的Wordpress插件。 I want to have HTML in the description field, but currently the JavaScript is outputting text, not translating it to HTML. 我想在说明字段中使用HTML,但是目前JavaScript正在输出文本,而不是将其翻译为HTML。

For instance, when the description is 例如,当描述是

Test <p>html</p>

It prints it with the <p> , instead of rendering a new paragraph. 它使用<p>打印,而不呈现新的段落。

function appendPersonality(quiz, personality, hasTitle, hasImage, hasDescription) {
  var $personality, $title, $description, $image;

  $title = createIf(hasTitle, '<h2>', { 'html': personality.name });

  if (personality.image.file) {
    $image = createIf(hasImage, '<img>', {
      'class': classes('result-image'),
      'src': _getPath(personality.image.file.path),
      'alt': personality.image.alt
    });
  }

  $description = createIf(hasDescription, '<p>', {
    'html': personality.description
  });

  // NOTE (Emil): We only create $personality element if it has at least
  // one child element.
  if (hasTitle || hasImage || hasDescription) {
    $personality = $('<div>', { 'class': classes('personality') });

    $personality.append($title);
    $personality.append($image);
    $personality.append($description);
  }

  quiz.$resultWrapper.append($personality);

  setInlineImageHeight($image, $personality, quiz.$resultWrapper);

  return $personality;
}

Why does 'html': personality.description not render html? 为什么'html': personality.description无法呈现html?

I took at the codes you posted, it should be fine. 我看了您发布的代码,应该没问题。 But my suggestion is to check the value of personality.description , it might be escaped at some point. 但是,我的建议是检查的价值personality.description ,它可能会在某个时候进行转义。 you can unescape it using 您可以使用以下方法取消转义

(The function unescapeHTML is taken from Arun P Johny's answer ) (函数unescapeHTML来自Arun P Johny的答案

function unescapeHtml(safe) {
    return safe.replace(/&amp;/g, '&')
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&quot;/g, '"')
        .replace(/&#039;/g, "'");
}

...

$description = createIf(hasDescription, '<p>', {
  'html': unescapeHtml(personality.description)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM