在Javascript中添加html

时间:2017-04-09 09:51:15

标签: javascript html wordpress

我正在尝试编辑使用JavaScript的Wordpress插件。我想在描述字段中包含HTML,但目前JavaScript正在输出文本,而不是将其翻译为HTML。

例如,当描述为

  

Test <p>html</p>

它使用<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;
}

为什么'html': personality.description不呈现html?

1 个答案:

答案 0 :(得分:0)

我看了你发布的代码,应该没问题。但我的建议是检查personality.description的值,它可能会在某个时候被转义。你可以使用

来解决它

(函数unescapeHTML取自Arun P Johny's answer

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)
});