如何只选择jQuery标签之外的文本 [英] How to only select text outside of a tag in jQuery

查看:88
本文介绍了如何只选择jQuery标签之外的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行用于客户端的Wordpress站点上的文本高亮搜索脚本。该脚本对网页上的原始HTML数据执行正则表达式搜索,并将span标记/ css元素添加到与查询匹配的文档的任何部分。



然而,我试图在一些多层次的HTML(头文件等)上进行搜索,其中一些标签具有描述性的id和类名,这些名称实际上最终通过脚本找到并突出显示。当脚本在其中一个 id 名称中找到匹配项时(例如:搜索Cont将转向< ; div id =Container> 转换为< div id =< span class =highlight> Cont< / span> ainer>

所以,我想知道如果有一种方法可以区分将显示在页面上的真实文本和原始HTML,以便仅 突出显示实际显示的HTML元素。



谢谢!

解决方案

删除我的第一篇文章以避免混淆它回答了主题问题。)但在你的情况下,应该使用不同的方法,我想:

1)通过...获取所有文本节点

  var textNodes = $('body')。find('*')。contents()。filter(function(){
返回this.nodeType === 3});

2)使用一些替换操作突出显示搜索字词:

  var term ='xxx'; 
textNodes.each(function(){
var $ this = $(this);
var content = $ this.text();
content = content.replace(term ,'< span class =highlight>'+ term +'< / span>');
$ this.replaceWith(content);
}


I'm trying to implement a text-highlighting search script on a Wordpress site for a client. The script executes a regex search on the raw HTML data from the webpage, adding a span tag/css element to any part of the document that matches the query.

However, I'm trying to search on some multi-level HTML (headers, etc), and some of the tags have descriptive id and class names, which actually end up getting found by the script and highlighted. This results in some wonky behavior when the script finds a match in one of the id names (ex: a search for "Cont" would wrap turn <div id="Container"> into <div id="<span class="highlight">Cont</span>ainer">.

This is obviously not what I want.

So, I'm wondering if there is a way to differentiate between "real text" that will show up on the page, and raw HTML, so that I can only highlight elements of the HTML that will actually be displayed.

Thanks!

解决方案

I deleted my first post to avoid the confusion, although it answered the topic question. ) But in your case a different approach should be used, I suppose:

1) get all the text nodes by...

var textNodes = $('body').find('*').contents().filter(function() { 
  return this.nodeType === 3 });

2) highlight the search term with some replacement op:

var term = 'xxx';
textNodes.each(function() {
  var $this = $(this);
  var content = $this.text();
  content = content.replace(term, '<span class="highlight">' + term + '</span>');
  $this.replaceWith(content);
}

这篇关于如何只选择jQuery标签之外的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆