我正在寻找一种简单的方法来遍历Angularjs中给定字符串的DOM(或元素)。如果找到了给定的字符串,我想将其文本加粗。由于尚未提出解决方案,因此我已经对此进行了思考。

例如

搜索应该返回4个结果

<section id="container">
  <div>
    <h2>Dogs are great</h2>
    <p>They are the best. Everyone should have a dog</p>
    <div>
      <p>Cat owners are just confused dog owners</p>
      <p>What's your doggos name?</p>
    </div>
  </div>
</section>

<script>
$scope.search = function(word){
    var entireDom = // Get the entire innerText of the <section>
    if(entireDom.match(word) {
      // Wrap the string in <strong> tags & update the DOM somehow?
      // This function should probably be case insensitive
    }
}
<script>

任何想法或技巧都将非常有帮助。谢谢!

最佳答案

这将逻辑不加区分地应用于文档正文的整个innerHTML:

document.body.innerHTML = document.body.innerHTML.replace(/(dog)/gi, '<strong>$1</strong>');

我不会在有 child 的节点上这样做。如果搜索“div”会怎样?如果您想更好地控制哪些节点,则可以仅在innerHTML特定节点上执行以下操作来替换正则表达式:
Array.prototype.slice.call(document.body.getElementsByTagName("*"))
  .forEach(f => {
    if(f.children.length === 0) f.innerHTML = f.innerHTML.replace(/(dog)/gi, '<strong>$1</strong>')
  });

看到这里:https://jsfiddle.net/kbLvdvh9/

这确实会更改DOM。向这些节点添加带有类的跨度可能会更容易,因此在搜索新单词或其他内容时可以关闭高亮显示。

关于javascript - 在Angularjs中的DOM扫描DOM,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45645228/

10-12 13:02
查看更多