Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.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
Javascript 无法在jQuery中突出显示具有特殊字符的单词_Javascript_Jquery - Fatal编程技术网

Javascript 无法在jQuery中突出显示具有特殊字符的单词

Javascript 无法在jQuery中突出显示具有特殊字符的单词,javascript,jquery,Javascript,Jquery,我有一个HTML页面,如下所示。我想突出显示内部有特殊字符的单词。例如,我正在搜索C#,但C#没有突出显示,其他没有特殊字符的单词也会突出显示。有什么问题吗?我已经包括了用于突出显示的jquery index.html <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1

我有一个HTML页面,如下所示。我想突出显示内部有特殊字符的单词。例如,我正在搜索C#,但C#没有突出显示,其他没有特殊字符的单词也会突出显示。有什么问题吗?我已经包括了用于突出显示的jquery

index.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Example</title>
<style>
  body { min-height: 100vh;background-image: linear-gradient(to right, #74ebd5 0%, #9face6 100%); }
  .container { margin: 150px auto; max-width: 640px; font-family: 'Raleway'; line-height: 1.8;}
    .highlight {background: #FFCD69;color:#222; padding: 5px 10px; border-radius: 3px;}
  </style>
</head>
<body>
  <div class="container">
  <h1>C C++ C# Java</h1>
  <h1>Java is a programming language</h1>
  </div>
  <div class="container">
  <p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's 
  standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make 
  a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, 
  remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, 
  and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
  <h1>Java is a programming language</h1>
  </div>
   <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  <script type="text/javascript" src="jquery.highlight.js"></script>
  <script>

         $('.container').each(function () {
            $(this).highlight("c#",
            {
                wordsOnly: true, wordsBoundary: '\\b\\W*'
            });
        });
  </script>
</body>
</html>

实例
身体{最小高度:100vh;背景图像:线性渐变(向右,#74ebd5 0%,#9face6 100%)}
.container{margin:150px auto;最大宽度:640px;字体系列:'ralway';行高:1.8;}
.突出显示{背景:#FFCD69;颜色:#222;填充:5px 10px;边框半径:3px;}
C C++语言java
Java是一种编程语言

Lorem Ipsum只是印刷和排版行业的虚拟文本。Lorem Ipsum一直是该行业的佼佼者
自16世纪以来,标准的虚拟文本,当时一位不知名的印刷商拿起一个打印工具,将其拼凑成
样书。它不仅存活了五个世纪,而且还跨越了电子排版,
基本保持不变。它在20世纪60年代随着包含Lorem Ipsum段落的Letraset表的发行而流行,
最近,像Aldus PageMaker这样的桌面发布软件包括Lorem Ipsum版本

Java是一种编程语言 $('.container')。每个(函数(){ $(此)。突出显示(“c#”), { 仅限单词:true,单词边界:'\\b\\W*' }); });
jquery.highlight.js


/*
*jQuery突出显示插件
*
*基于Johann Burkard的highlight v3
* http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
*
*代码经过一点重构和清理(以我的拙见)。
*最重要的变化:
*-可选择仅突出显示整个单词(默认情况下为-false),
*-具有区分大小写的选项(区分大小写-默认为false)
*-高亮显示元素标记,可以在选项中指定类名
*
*用法:
*//在内容中包装每次出现的文本“lorem”
*//使用(默认选项)
*$('#content')。突出显示('lorem');
*
*//一次搜索并突出显示更多术语
*//这样可以节省一些遍历DOM的时间
*$('content')。突出显示(['lorem','ipsum');
*$(“#内容”)。突出显示(“lorem ipsum”);
*
*//仅搜索整个单词“lorem”
*$('content')。突出显示('lorem',{wordsOnly:true});
*
*//仅搜索整个单词“C#”
*//并确保单词边界也可以
*//是一个“非单词”字符,也是一个仅限regex-latin1的边界:
*$(“#内容”)。突出显示('C#',{wordsOnly:true,wordsBoundary:'[\\b\\W]});
*
*//搜索术语“lorem”时不要忽略大小写
*$('content')。突出显示('lorem',{区分大小写:true});
*
*//将每次出现的术语“ipsum”都包装在内容中
*//与
*$('content')。突出显示('ipsum',{element:'em',className:'important'});
*
*//删除默认突出显示
*$(“#内容”).unhighlight();
*
*//删除自定义突出显示
*$(#content').unhighlight({element:'em',className:'important'});
*
*
*版权所有(c)2009 Bartek Szopka
*
*获得麻省理工学院许可证。
*
*/
(功能(工厂){
if(typeof define=='function'&&define.amd){
//AMD。注册为匿名模块。
定义(['jquery'],工厂);
}else if(导出的类型==='object'){
//节点/公共JS
工厂(require('jquery'));
}否则{
//浏览器全局
工厂(jQuery);
}
}(函数(jQuery){
jQuery.extend({
突出显示:函数(节点、re、节点名、类名、回调){
if(node.nodeType==3){
var match=node.data.match(re);
如果(匹配){
//新的高亮显示元素节点
var highlight=document.createElement(nodeName | | |'span');
highlight.className=className | |“highlight”;
//请注意,我们使用捕获的值来查找实际索引
//这是因为我们不希望包含匹配的单词边界
var capturePos=node.data.indexOf(match[1],match.index);
//拆分节点并替换匹配的wordnode
//使用高亮显示的节点
var wordNode=node.splitText(capturePos);
wordNode.splitText(匹配[1]。长度);
var wordClone=wordNode.cloneNode(true);
突出显示.appendChild(wordClone);
wordNode.parentNode.replaceChild(高亮显示,wordNode);
if(回调类型=='function'){
回调(突出显示)
}
返回1;//跳过父节点中添加的节点
}
}else if((node.nodeType==1&&node.childNodes)&&&//仅包含子元素的元素节点
!/(script | style)/i.test(node.tagName)&&&//忽略脚本和样式节点
!(node.tagName===nodeName.toUpperCase()&&node.className===className)){//如果已经高亮显示,则跳过
对于(var i=0;i/*
 * jQuery Highlight plugin
 *
 * Based on highlight v3 by Johann Burkard
 * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
 *
 * Code a little bit refactored and cleaned (in my humble opinion).
 * Most important changes:
 *  - has an option to highlight only entire words (wordsOnly - false by default),
 *  - has an option to be case sensitive (caseSensitive - false by default)
 *  - highlight element tag and class names can be specified in options
 *
 * Usage:
 *   // wrap every occurrence of text 'lorem' in content
 *   // with <span class='highlight'> (default options)
 *   $('#content').highlight('lorem');
 *
 *   // search for and highlight more terms at once
 *   // so you can save some time on traversing DOM
 *   $('#content').highlight(['lorem', 'ipsum']);
 *   $('#content').highlight('lorem ipsum');
 *
 *   // search only for entire word 'lorem'
 *   $('#content').highlight('lorem', { wordsOnly: true });
 *
 *   // search only for the entire word 'C#'
 *   // and make sure that the word boundary can also
 *   // be a 'non-word' character, as well as a regex latin1 only boundary:
 *   $('#content').highlight('C#', { wordsOnly: true , wordsBoundary: '[\\b\\W]' });
 *
 *   // don't ignore case during search of term 'lorem'
 *   $('#content').highlight('lorem', { caseSensitive: true });
 *
 *   // wrap every occurrence of term 'ipsum' in content
 *   // with <em class='important'>
 *   $('#content').highlight('ipsum', { element: 'em', className: 'important' });
 *
 *   // remove default highlight
 *   $('#content').unhighlight();
 *
 *   // remove custom highlight
 *   $('#content').unhighlight({ element: 'em', className: 'important' });
 *
 *
 * Copyright (c) 2009 Bartek Szopka
 *
 * Licensed under MIT license.
 *
 */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function (jQuery) {
    jQuery.extend({
        highlight: function (node, re, nodeName, className, callback) {
            if (node.nodeType === 3) {
                var match = node.data.match(re);
                if (match) {
                    // The new highlight Element Node
                    var highlight = document.createElement(nodeName || 'span');
                    highlight.className = className || 'highlight';
                    // Note that we use the captured value to find the real index
                    // of the match. This is because we do not want to include the matching word boundaries
                    var capturePos = node.data.indexOf( match[1] , match.index );

                    // Split the node and replace the matching wordnode
                    // with the highlighted node
                    var wordNode = node.splitText(capturePos);
                    wordNode.splitText(match[1].length);

                    var wordClone = wordNode.cloneNode(true);
                    highlight.appendChild(wordClone);
                    wordNode.parentNode.replaceChild(highlight, wordNode);
                    if (typeof callback == 'function') {
                        callback(highlight)   
                    }
                    return 1; //skip added node in parent
                }
            } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
                    !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
                    !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
                for (var i = 0; i < node.childNodes.length; i++) {
                    i += jQuery.highlight(node.childNodes[i], re, nodeName, className, callback);
                }
            }
            return 0;
        }
    });

    jQuery.fn.unhighlight = function (options) {
        var settings = {
          className: 'highlight',
          element: 'span'
        };

        jQuery.extend(settings, options);

        return this.find(settings.element + '.' + settings.className).each(function () {
            var parent = this.parentNode;
            parent.replaceChild(this.firstChild, this);
            parent.normalize();
        }).end();
    };

    jQuery.fn.highlight = function (words, options, callback) {
        var settings = {
          className: 'highlight',
          element: 'span',
          caseSensitive: false,
          wordsOnly: false,
          wordsBoundary: '\\b'
        };

        jQuery.extend(settings, options);

        if (typeof words === 'string') {
          words = [words];
        }
        words = jQuery.grep(words, function(word, i){
          return word != '';
        });
        words = jQuery.map(words, function(word, i) {
          return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
        });

        if (words.length === 0) {
          return this;
        };

        var flag = settings.caseSensitive ? '' : 'i';
        // The capture parenthesis will make sure we can match
        // only the matching word
        var pattern = '(' + words.join('|') + ')';
        if (settings.wordsOnly) {
            pattern =
                (settings.wordsBoundaryStart || settings.wordsBoundary) +
                pattern +
                (settings.wordsBoundaryEnd || settings.wordsBoundary);
        }
        var re = new RegExp(pattern, flag);

        return this.each(function () {
            jQuery.highlight(this, re, settings.element, settings.className, callback);
        });
    };
}));