本文介绍了正则表达式搜索html返回,但不是实际的html jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个突出显示插件,供客户端在页面中查找内容,因此我决定在仍在构建的帮助查看器中对其进行测试,但是我遇到了一个问题(可能)需要一些正则表达式.

I'm making a highlighting plugin for a client to find things in a page and I decided to test it with a help viewer im still building but I'm having an issue that'll (probably) require some regex.

我不想解析HTML,并且我完全公开了如何以不同的方式执行此操作,这似乎是最好/正确的方法.

I do not want to parse HTML, and im totally open on how to do this differently, this just seems like the the best/right way.

http://oscargodson.com/labs/help-viewer

http://oscargodson.com/labs/help-viewer/js/jquery.jhighlight.js

在搜索中键入内容...好的,刷新页面,现在键入classclass="或键入<a,您会发现它将搜索实际的HTML(按预期).我怎么只能搜索文本?

Type something in the search... ok, refresh the page, now type, like, class or class=" or type <a you'll notice it'll search the actual HTML (as expected). How can I only search the text?

如果我做.text(),它将使所有HTML蒸发,我得到的只是一大堆文本,但是我仍然想要HTML,因此我不会丢失格式,链接,图像等.我想要就像CMD/CTRL + F一样.

If i do .text() it'll vaporize all the HTML and what i get back will just be a big blob of text, but i still want the HTML so I dont lose formatting, links, images, etc. I want this to work like CMD/CTRL+F.

您将使用此插件,例如:

You'd use this plugin like:

$('article').jhighlight({find:'class'});

要删除它们:

.jhighlight('remove')

== UPDATE ==

虽然下面的Mike Samuel的想法确实可行,但对于此插件而言却有点繁重.它主要用于希望在表单的发布"过程中删除不良单词和/或MS Word字符的客户端.我正在寻找更轻巧的修复程序,有什么想法吗?

While Mike Samuel's idea below does in fact work, it's a tad heavy for this plugin. It's mainly for a client looking to erase bad words and/or MS Word characters during a "publishing" process of a form. I'm looking for a more lightweight fix, any ideas?

推荐答案

您真的不想使用eval,与innerHTML混淆或手动"解析标记.我认为,最好的方法是直接处理文本节点,并保留原始html的缓存以擦除突出显示.快速重写,并带有注释:

You really don't want to use eval, mess with innerHTML or parse the markup "manually". The best way, in my opinion, is to deal with text nodes directly and keep a cache of the original html to erase the highlights. Quick rewrite, with comments:

(function($){
  $.fn.jhighlight = function(opt) {

    var options = $.extend($.fn.jhighlight.defaults, opt)
      , txtProp = this[0].textContent ? 'textContent' : 'innerText';

    if ($.trim(options.find.length) < 1) return this;

    return this.each(function(){

      var self = $(this);

      // use a cache to clear the highlights
      if (!self.data('htmlCache'))
        self.data('htmlCache', self.html());

      if(opt === 'remove'){
        return self.html( self.data('htmlCache') );
      }

     // create Tree Walker
     // https://developer.mozilla.org/en/DOM/treeWalker
     var walker = document.createTreeWalker(
          this, // walk only on target element
          NodeFilter.SHOW_TEXT,
          null,
          false
      );

      var node
        , matches
        , flags = 'g' + (!options.caseSensitive ? 'i' : '')
        , exp = new RegExp('('+options.find+')', flags) // capturing
        , expSplit = new RegExp(options.find, flags) // no capturing
        , highlights = [];

      // walk this wayy
      // and save matched nodes for later
      while(node = walker.nextNode()){
        if (matches = node.nodeValue.match(exp)){
          highlights.push([node, matches]);
        }
      }

      // must replace stuff after the walker is finished
      // otherwise replacing a node will halt the walker
      for(var nn=0,hln=highlights.length; nn<hln; nn++){

        var node = highlights[nn][0]
          , matches = highlights[nn][1]
          , parts = node.nodeValue.split(expSplit) // split on matches
          , frag = document.createDocumentFragment(); // temporary holder

        // add text + highlighted parts in between
        // like a .join() but with elements :)
        for(var i=0,ln=parts.length; i<ln; i++){

          // non-highlighted text
          if (parts[i].length)
            frag.appendChild(document.createTextNode(parts[i]));

          // highlighted text
          // skip last iteration
          if (i < ln-1){
            var h = document.createElement('span');
            h.className = options.className;
            h[txtProp] = matches[i];
            frag.appendChild(h);
          }
        }
        // replace the original text node
        node.parentNode.replaceChild(frag, node);
      };

    });
  };

 $.fn.jhighlight.defaults = {
    find:'',
    className:'jhighlight',
    color:'#FFF77B',
    caseSensitive:false,
    wrappingTag:'span'
 };

})(jQuery);

如果您要在页面上进行任何操作,则可能要用另一种清理机制来替换缓存,尽管这种机制并不简单.

If you're doing any manipulation on the page, you might want to replace the caching with another clean-up mechanism, not trivial though.

您可以在此处查看代码: http://jsbin.com/anace5/2/

You can see the code working here: http://jsbin.com/anace5/2/

您还需要将display:block添加到新的html元素中,在某些浏览器中布局已损坏.

You also need to add display:block to your new html elements, the layout is broken on a few browsers.

这篇关于正则表达式搜索html返回,但不是实际的html jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 06:30