简体   繁体   English

突出显示电话号码并用标签javascript包装

[英]Highlight phone number and wrap with tag javascript

The following code checks if the selected tag has childnodes. 以下代码检查所选标签是否具有子节点。 If a child node is present , it loops till a child node is found. 如果存在子节点,则该子节点循环直到找到子节点。 When there are no further child nodes found, it loops out ie it reaches a text node causing the loop to end. 当没有其他子节点找到时,它将循环退出,即到达文本节点,导致循环结束。 The function is made recursive to run until no child node is found. 使该函数递归运行,直到找不到子节点为止。 The code runs as per above info, but when I try to match TEXT_NODE ( console.log() outputs all text node), replace() is used to identify phone numbers using regex and replaced with hyperlink. 该代码按照上述信息运行,但是当我尝试匹配TEXT_NODEconsole.log()输出所有文本节点)时, replace()用于使用正则表达式标识电话号码,并替换为超链接。 The number gets detected and is enclosed with a hyperlink but it gets displayed twice ie number enclosed with hyperlink and only the number.Following is the code 该数字被检测到并用超链接括起来,但是会显示两次,即用超级链接括起来的数字只有数字。下面是代码

            function DOMwalker(obj){
            var regex = /\+\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}/g;
             var y = "<a href=\"javascript:void(0);\">$&</a>";
            if(obj.hasChildNodes()){
                var child = obj.firstChild;

                while(child){
                    if(child.nodeType!==3)
                    {
                        DOMwalker(child);
                    }
                    if (child.nodeType=== 3) {
                            var text = child.nodeValue;
                             console.log(typeof text);                            
                            var regs = regex.exec(text);

                            match = text.replace(regex,y);

                            if(match){

                                var item = document.createElement('a');
                                item.setAttribute('href','javascript:void(0);');
                                var detect = document.createTextNode(match);
                                var x=item.appendChild(detect);
                                console.log(x);
                               child.parentNode.insertBefore(x,child);
                           }
                     }

                     child=child.nextSibling;
                }
            }
        };
        $(window).load(function(){
            var tag = document.querySelector(".gcdMainDiv div.contentDiv");

            DOMwalker(tag);
        });

Following are the screenshot of the output: 以下是输出的屏幕截图: 在此处输入图片说明

Here the number gets printed twice instead of one with hyperlink which is been displayed(expected highlighted number with hyperlink) and second widout tags 在这里,数字被打印两次,而不是被显示的带有超链接的数字(带有超链接的预期突出显示的数字)和第二个淘汰标记

Following is console.log of x 以下是x console.log 在此处输入图片说明

I have already gone through this . 我已经经历过

The solution provided below works well with FF. 提供的解决方案下面用FF效果很好。 The problem arises when used in IE11. 在IE11中使用时会出现问题。 It throws Unknown runtime error and references the .innerHTML . 它引发Unknown runtime error并引用.innerHTML I used the appenChild(),but the error couldn't be resolved. 我使用了appenChild(),但无法解决该错误。

You've got a couple of problems with what you posted. 您发布的内容存在一些问题。 First, if a child is not node type 3 and not a SCRIPT node, you re-call recursivetree() but you do not pass the child in. The function will just start over at the first div element and again, infinitely loop. 首先,如果子节点不是3型节点,也不是SCRIPT节点,则重新调用recursivetree()但不要传递该子节点。该函数将从第一个div元素重新开始,然后无限循环。

Second, you're calling replace() on the node itself, and not the node's innerHTML . 其次,您要在节点本身而不是节点的innerHTML上调用replace() You're trying to replace a node with a string, which just won't work, and I think you mean to replace any matching numbers within that node, rather than the entire node. 您正在尝试用字符串替换节点,但这将无法正常工作,我想您的意思是替换该节点内的所有匹配数字,而不是整个节点。

If you have <div>My number is +111-555-9999</div> , you only want to replace the number and not lose everything else. 如果您有<div>My number is +111-555-9999</div> ,则只希望替换该号码,而不丢失其他所有内容。

Try this as a solution: 尝试以下解决方案:

function recursivetree(obj){
   var regex = /\+\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}/g;
   var y = "<a href=\"javascript:;\">$&</a>";
   var obj = obj || document.getElementsByTagName('div')[0];
   if(obj.hasChildNodes()){
       var child = obj.firstChild;
       while(child){
           if(child.nodeType !== 3 && child.nodeName !== 'SCRIPT'){
                  //Recall recursivetree with the child 
                  recursivetree(child);
           }

           //A nodeType of 3, text nodes, sometimes do not have innerHTML to replace
           //Check if the child has innerHTML and replace with the regex
           if (child.innerHTML !== undefined) {
                child.innerHTML = child.innerHTML.replace(regex,y);
           }
           child=child.nextSibling;
       }
   }
}
recursivetree();

Fiddle: http://jsfiddle.net/q07n5mz7/ 小提琴: http : //jsfiddle.net/q07n5mz7/

Honestly? 说实话? If you're trying to loop through the entire page and replace all instances of numbers, just do a replace on the body. 如果您试图遍历整个页面并替换所有数字实例,则只需对正文进行替换即可。

var regex = /\+\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}/g;
var y = "<a href=\"javascript:;\">$&</a>";
var body = document.body;
body.innerHTML = body.innerHTML.replace(regex, y);

Fiddle: http://jsfiddle.net/hmdv7adu/ 小提琴: http : //jsfiddle.net/hmdv7adu/

Finally, I got the solution of my question. 最后,我得到了问题的解决方案。 I referred to this answer which helped me to solve my query. 我提到了这个答案 ,这有助于我解决查询。

Here goes the code: 代码如下:

            function DOMwalker(obj){
            if(obj.hasChildNodes()){
                var child = obj.firstChild;
                var children = obj.childNodes;
                var length = children.length;
                for(var i = 0;i<length;i++){
                    var nodes = children[i];
                    if(nodes.nodeType !==3){
                        DOMwalker(nodes);
                    }
                    if(nodes.nodeType===3){
                        //Pass the parameters nodes:current node being traversed;obj:selector being passed as parameter for DOMwalker function 
                        highlight(nodes,obj);
                    }
                }
                child = child.nextSibling;
            }
        }
        function highlight(node,parent){
            var regex =/(\d{1}-\d{1,4}-\d{1,5})|(\+\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9})/g;
            //Stores the value of current node which is passed through the if loop
            var matchs = node.data.match(regex);
            if matchs is true,add it to DOM
            if(matchs){
                var anchor = document.createElement("a");
                var y = /[(]\d[)]|[.-\s]/g;//removes spaces periods or dash,also number within brackets
                var remove = number.replace(y,'');
                //tel uri,if you have an app like skype for click-to dial
                anchor.setAttribute("href","tel:"+remove);
                //the anchor tag should be inserted before in the current node in the DOM
                parent.insertBefore(anchor,node);
                //append it toh the DOM to be displaye don the web page
                anchor.appendChild(node);

            }
            else
            {
                return false;
            }

        }

I hope this code helps others. 我希望这段代码对其他人有帮助。

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

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