javascript - 排除一些关于使用 jQuery 过滤 DOM 的区域

标签 javascript jquery

我正在过滤整个 DOM 以用其他字符串替换一些字符串。
为此,我编写了以下代码:

$('body :not(script)').contents().filter(function() {
  return this.nodeType === 3;
}).replaceWith(function() {
  return this.nodeValue.replace('T 0','T  0');
});
如何排除某些区域?例如,我想要类 .example 的 DIV不予考虑。
我尝试了以下方法:
$('body :not(script):not(.example)').contents().filter(function() {
  return this.nodeType === 3;
}).replaceWith(function() {
  return this.nodeValue.replace('T 0','T  0');
});
为什么这似乎不起作用?

最佳答案

现在,你告诉 jQuery 排除节点 .example ,它有子节点,将被包括在内。
在您的 :not()选择器添加 *课后。这将告诉 jQuery 排除父节点下的所有节点。
在 CSS 中 *universal selector

The CSS universal selector (*) matches elements of any type.


这是一个工作版本:
(请注意,我将   更改为 - 以直观地显示更改)

$( "input:not(:checked) + span" ).css( "background-color", "yellow" );
$( "input").attr( "disabled", "disabled" );

$('body :not(script):not(div.example *)').contents().filter(function() {
  return this.nodeType === 3;
}).replaceWith(function() {
  return this.nodeValue.replace('T 0','T--0');
});
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>not demo</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

<div class="example">
  <p>Remains the same:</p>
  <h1>T 0</h1>
</div>

<div>
  <p>Changes:</p>
  <h1>T 0</h1>
</div>
 
</body>
</html>

关于javascript - 排除一些关于使用 jQuery 过滤 DOM 的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70363689/

相关文章:

javascript - 为什么当我在单独的函数中使用 $(this) 并在 .each() 中调用它时它不起作用?

javascript - 如何使用 javascript 或 jquery 删除/删除单词的第一个空格?

jquery - 动画切换滑动菜单

javascript - 无法使用 Excel JavaScript API 设置 NumberFormat

jquery - 图像 slider 无法正常工作

javascript - 在 JavaScript/jQuery 中连接字符串?

c# - 如何在 .NET 中使 Google 可抓取 AJAX 分页

javascript - Backbone.js 单例集合

javascript - 没有类的 Typescript 中的 Getter/Setter

javascript - 在 JavaScript 中嵌入 ruby​​,无法识别 ruby