我正在过滤整个 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/