Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在html文档中使用javascript动态寻址单词/字符串,然后对其进行标记?_Javascript_Html_Dom_Dom Traversal - Fatal编程技术网

如何在html文档中使用javascript动态寻址单词/字符串,然后对其进行标记?

如何在html文档中使用javascript动态寻址单词/字符串,然后对其进行标记?,javascript,html,dom,dom-traversal,Javascript,Html,Dom,Dom Traversal,我有一个HTML文档: <html> <body> <p> A funny joke: <ul> <li>do you know why six is afraid of seven? <li>because seven ate nine. </ul> Oh, so funny! </p> <

我有一个HTML文档:

<html>
  <body>
    <p>
      A funny joke:
      <ul>
        <li>do you know why six is afraid of seven?
        <li>because seven ate nine.
      </ul>
      Oh, so funny!
    </p>
  </body>
</html>


一个有趣的笑话:
  • 你知道为什么六怕七吗?
  • 因为七吃九。
哦,真有趣!

现在我想识别第一个出现的“seven”,并用

<span id="link1" class="link">

如何做到这一点

您是否必须解析DOM树,或者是否可以在body部分中获取整个代码,然后搜索单词

在这两种情况下,当我在某个地方找到这个单词后,如何识别它并将它的DOM parent更改为span(我想这就是必须要做的),然后添加提到的属性

这不是我期望的那么多代码,而是什么方法或概念可以完成这项工作


我对框架解决方案并不感兴趣,而是对纯javascript方式感兴趣。

我发现了以下问题:


这看起来很接近你想要做的事情。现在,您是试图仅包装文本“seven”还是试图包装
  • 的全部内容?

    我发现了以下问题:


    这看起来很接近你想要做的事情。现在,您是在尝试仅包装文本“seven”还是在尝试包装
  • 的全部内容?

    您需要找到一个类型为text\u node(3)且包含预期单词的DOM节点。当需要将节点拆分为三个节点时

    第一个是文本节点,其中包含搜索词之前的文本,第二个是包含搜索词的跨度节点,第三个是另一个文本节点,包含原始节点的尾部(均在搜索词之后)

    这里是一个源代码

    <html>
       <head>
          <style type="text/css">
             .link {
                color: red;
             }
          </style>
       </head>
      <body>
        <p>
          A funny joke:
          <ul>
            <li>do you know why six is afraid of seven?
            <li>because seven ate nine.
          </ul>
          Oh, so funny!
        </p>
        <script type="text/javascript">
           function search(where, what) {
             var children = where.childNodes;
             for(var i = 0, l = children.length; i < l; i++) {
                var child = children[i], pos;
                if(child.nodeType == 3 && (pos = child.nodeValue.indexOf(what)) != -1) { // a TEXT_NODE
                   var value = child.nodeValue;
                   var parent = child.parentNode;
                   var start = value.substring(0, pos);
                   var end = value.substring(pos + what.length);
                   var span = document.createElement('span');
    
                   child.nodeValue = start;
                   span.className = 'link';
                   span.id = 'link1';
                   span.innerHTML = what;
                   parent.appendChild(span);
                   parent.appendChild(document.createTextNode(end));
                   return true;
                } else
                   if(search(child, what))
                      break;
             }
             return false;
           }
           search(document.getElementsByTagName('body')[0], 'seven');
        </script>
      </body>
    </html>
    
    
    .链接{
    颜色:红色;
    }
    
    一个有趣的笑话:
    
    • 你知道为什么六怕七吗?
    • 因为七吃九。
    哦,真有趣!

    函数搜索(何处、何处){ var children=where.childNodes; for(变量i=0,l=children.length;i
    您需要找到一个类型为TEXT\u node(3)的DOM节点,该节点包含您想要的单词。当需要将节点拆分为三个节点时

    第一个是文本节点,其中包含搜索词之前的文本,第二个是包含搜索词的跨度节点,第三个是另一个文本节点,包含原始节点的尾部(均在搜索词之后)

    这里是一个源代码

    <html>
       <head>
          <style type="text/css">
             .link {
                color: red;
             }
          </style>
       </head>
      <body>
        <p>
          A funny joke:
          <ul>
            <li>do you know why six is afraid of seven?
            <li>because seven ate nine.
          </ul>
          Oh, so funny!
        </p>
        <script type="text/javascript">
           function search(where, what) {
             var children = where.childNodes;
             for(var i = 0, l = children.length; i < l; i++) {
                var child = children[i], pos;
                if(child.nodeType == 3 && (pos = child.nodeValue.indexOf(what)) != -1) { // a TEXT_NODE
                   var value = child.nodeValue;
                   var parent = child.parentNode;
                   var start = value.substring(0, pos);
                   var end = value.substring(pos + what.length);
                   var span = document.createElement('span');
    
                   child.nodeValue = start;
                   span.className = 'link';
                   span.id = 'link1';
                   span.innerHTML = what;
                   parent.appendChild(span);
                   parent.appendChild(document.createTextNode(end));
                   return true;
                } else
                   if(search(child, what))
                      break;
             }
             return false;
           }
           search(document.getElementsByTagName('body')[0], 'seven');
        </script>
      </body>
    </html>
    
    
    .链接{
    颜色:红色;
    }
    
    一个有趣的笑话:
    
    • 你知道为什么六怕七吗?
    • 因为七吃九。
    哦,真有趣!

    函数搜索(何处、何处){ var children=where.childNodes; for(变量i=0,l=children.length;i
    这是我几年前编写的一个函数,用于搜索特定文本并突出显示它们(将点击的内容放入带有特定类名的
    span

    它遍历DOM树,检查文本内容。每当它找到包含查找的文本的文本节点时,它将用三个新节点替换该文本节点:

  • 一个文本节点,其文本位于匹配之前
  • 一个(新创建的)包含匹配文本的
    span
    元素
  • 和一个文本节点,其中文本位于匹配之后
  • 这就是我所拥有的函数。它是较大脚本文件的一部分,但也应该独立运行。(我已经注释掉了对
    ensureElementVisible
    的调用,该调用使元素可见,因为脚本还具有折叠和扩展功能)

    它做了一件(其他)您可能不需要的事情:它将搜索文本转换为与多个单词中的任何一个匹配的正则表达式

    function findText(a_text, a_top) {
        // Go through *all* elements below a_top (if a_top is undefined, then use the body)
        //  and check the textContent or innerText (only if it has textual content!)
        var rexPhrase = new RegExp(a_text.replace(/([\\\/\*\?\+\.\[\]\{\}\(\)\|\^\$])/g, '\\$1').replace(/\W+/g, '\\W*')
                                        , 'gi');
        var terms = [];
        var rexSearchTokens = /[\w]+/g;
        var match;
        while(match = rexSearchTokens.exec(a_text)) {
            terms.push(match[0]);
        }
        var rexTerm = new RegExp('\\b(' + terms.join('|') + ')', 'gi');
    
        var hits = [];
        walkDOMTree(a_top || document.body,
                    function search(a_element) {
                        if (a_element.nodeName === '#text') {
                            if(rexPhrase.test(a_element.nodeValue)) {
    //                          ensureElementVisible(a_element, true);
                                hits.push(a_element);
                            }
                        }
                    });
    
        // highlight the search terms in the found elements
        for(var i = 0; i < hits.length; i++) {
            var hit = hits[i];
            var parent = hit.parentNode;
    
            if (parent.childNodes.length === 1) {
                // Remove the element from the hit list
                hits.splice(i, 1);
    
                var text = hit.nodeValue;
                parent.removeChild(hit);
                var match, prevLastIndex = 0;
                while(match = rexTerm.exec(text)) {
                    parent.appendChild(document.createTextNode(text.substr(prevLastIndex, match.index - prevLastIndex)));
                    var highlightedTerm = parent.appendChild(document.createElement('SPAN'));
                    highlightedTerm.className = 'search-hit';
                    highlightedTerm.appendChild(document.createTextNode(match[0]));
                    prevLastIndex = match.index + match[0].length;
    
                    // Insert the newly added element into the hit list
                    hits.splice(i, 0, highlightedTerm);
                    i++;
                }
                parent.appendChild(document.createTextNode(text.substr(prevLastIndex)));
    
                // Account for the removal of the original hit node
                i--;
            }
        }
    
        return hits;
    }
    
    函数findText(a_text,a_top){
    //检查\u top下面的*all*元素(如果未定义\u top,则使用主体)
    //并检查textContent或innerText(仅当它有文本内容时!)