2

我正在构建一个搜索自动建议组件,其中结果使用 hyperHTML 呈现。从服务器返回的建议的匹配字符串部分应突出显示。

我正在使用正则表达式并String.prototype.replace突出显示匹配的部分,但不知何故我无法将它的返回值输出到 HTML。它只是将标签呈现<strong>为字符串。

我尝试了很多不同的方法来解决这个问题,但没有任何成功并且我的想法已经用完了......

这是我的渲染功能:

const suggestionsContainer = document.querySelector(
  ".js-suggestions-container"
);
const suggestions = [{
    title: "lorem ipsum dolor sit amet",
    url: "#"
  },
  {
    title: "lorem ipsum dolor sit amet",
    url: "#"
  }
];
let query = "ipsum";

function renderSuggestions(suggestions, query) {
  const queryRegEx = new RegExp(query, "gi");
  hyperHTML.bind(suggestionsContainer)`
      ${suggestions.map((suggestion) => hyperHTML.wire(suggestion)`
        <a href="${suggestion.url}">
          ${hyperHTML.wire()`${suggestion.title.replace(queryRegEx, "<strong>$&</strong>")}`}
        </a>
      `)}
  `;
}

renderSuggestions(suggestions, query);
a {
  display: block;
  margin: 1rem 0;
}
<script src="https://unpkg.com/hyperhtml@latest/min.js"></script>
<div class="js-suggestions-container"></div>

4

1 回答 1

2

正如您在此 CodePen 中看到的,您需要的唯一更改是明确要求html

  ${suggestions.map((suggestion) => hyperHTML.wire(suggestion)`
    <a href="${suggestion.url}">
      ${{html: suggestion.title.replace(queryRegEx, "<strong>$&</strong>")}}
    </a>
  `)}

{html: ...}是最明显的方式,但hyperHTML也将数组作为 HTML 注入,但这可能是出乎意料的,而较轻的 HTML和微型 html默认情况下都更安全,并且必须始终显式地注入内插内容。

PS 仅将文本作为内容进行布线也几乎不需要

于 2020-07-15T07:53:01.040 回答