[英]Hide content inside brackets using pure JavaScript
I want to use pure JavaScript to hide all content inside brackets in a document. 我想使用纯JavaScript来隐藏文档中括号内的所有内容。 For example, this:
例如,这个:
Sometext [info]
Sometext [info]
would be replaced with this: 将被替换为:
Sometext
Sometext
With jQuery I can do this with: 使用jQuery,我可以这样做:
<script type="text/javascript">
jQuery(document).ready(function(){
var replaced = jQuery("body").html().replace(/\[.*\]/g,'');
jQuery("body").html(replaced);
});
</script>
The document
's DOMContentLoaded
event will fire at the same time as the callback you pass to jQuery(document).ready(...)
. document
的DOMContentLoaded
事件将在您传递给jQuery(document).ready(...)
的回调的同时触发。
You can access the body of the page through document.body
instead of jQuery("body"), and modify the HTML using the .innerHTML
property instead of jQuery's .html()
method . 您可以通过
document.body
而不是jQuery(“body”)访问页面主体,并使用.innerHTML
属性而不是jQuery的.html()
方法修改HTML。
document.addEventListener("DOMContentLoaded", function(event) {
var replaced = document.body.innerHTML.replace(/\[.*\]/g,'');
document.body.innerHTML = replaced;
});
If you use, document.body.innerHTML to replace, it is going to replace everything between [], even valid ones like input names. 如果使用document.body.innerHTML替换,它将替换[]之间的所有内容,甚至是输入名称之类的有效内容。 So I think what you need is to grab all of the textnodes and then run the regex on them.
所以我认为你需要的是获取所有的文本节点,然后对它们运行正则表达式。 This question looks like it will do the trick.
这个问题看起来会成功。
function recurse(element)
{
if (element.childNodes.length > 0)
for (var i = 0; i < element.childNodes.length; i++)
recurse(element.childNodes[i]);
if (element.nodeType == Node.TEXT_NODE && /\S/.test(element.nodeValue)){
element.nodeValue = element.nodeValue.replace(/\[.*\]/g,'');
}
}
document.addEventListener('DOMContentLoaded', function() {
// This hits the entire document.
// var html = document.getElementsByTagName('html')[0];
// recurse(html);
// This touches only the elements with a class of 'scanME'
var nodes = document.getElementsByClassName('scanME');
for( var i = 0; i < nodes.length; i++) {
recurse(nodes[i]);
}
});
您已经有了解决方案,请尝试"Sometext [info]".replace(/\\[.*\\]/g,'');
Basically what your doing is this 基本上你在做什么就是这个
document.addEventListener('DOMContentLoaded', function() {
var replaced = document.body.innerHTML.replace(/\[.*\]/g,'');
document.body.innerHTML = replaced
});
That would be a silly idea though (speaking for myself) 那会是一个愚蠢的想法(为自己说话)
Make your life easier & your site better by doing something like this 做这样的事情,让你的生活更轻松,你的网站更好
<p> Sometext <span class="tag-variable"> [info] </span> </p>
document.addEventListener('DOMContentLoaded', function(){
var tags = document.getElementsByClassName('tag-variable');
for( var i = 0; i < tags.length; i++) {
var current = tags[i]; // Work with tag here or something
current.parentNode.removeChild( current );
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.