在网页的正文区域是唯一可访问的部分的情况下,是否有办法使用内联 JavaScript 或其他支持内联的语言删除特定文本短语(以 HTML 编写)的所有实例?
这在很多情况下都很有用,例如人们使用 Tiny.cc/customurl 并希望删除声明“tiny.cc/”的部分
如果细节允许,我们将使用 Tiny.cc 修改日历插件以创建自定义 URL (tiny.cc/customurl)。该插件默认显示完整的 URL,所以我们想去掉文本“tiny.cc/”并在我们的代码中保留“customurl”部分:
<div class="ews_cal_grid_custom_item_3">
<div class="ews_cal_grid_select_checkbox_clear" id="wGridTagChk" onclick="__doPostBack('wGridTagChk', 'tiny.cc/Baseball-JV');" > </div>
tiny.cc/Baseball-JV
</div>
我们要删除的部分是第 3 行的 http://tiny.cc/
本身。
最佳答案
要在不替换所有 HTML(这会破坏所有事件处理程序)的情况下执行此操作并且在不使用递归(通常更快)的情况下执行此操作,您可以这样做:
function removeText(top, txt) {
var node = top.firstChild, index;
while(node && node != top) {
// if text node, check for our text
if (node.nodeType == 3) {
// without using regular expressions (to avoid escaping regex chars),
// replace all copies of this text in this text node
while ((index = node.nodeValue.indexOf(txt)) != -1) {
node.nodeValue = node.nodeValue.substr(0, index) + node.nodeValue.substr(index + txt.length);
}
}
if (node.firstChild) {
// if it has a child node, traverse down into children
node = node.firstChild;
} else if (node.nextSibling) {
// if it has a sibling, go to the next sibling
node = node.nextSibling;
} else {
// go up the parent chain until we find a parent that has a nextSibling
// so we can keep going
while ((node = node.parentNode) != top) {
if (node.nextSibling) {
node = node.nextSibling;
break;
}
}
}
}
}
此处的工作演示:http://jsfiddle.net/jfriend00/2y9eH/
要对整个文档执行此操作,您只需调用:
removeText(document.body, "http://tiny.cc/Baseball-JV");
关于javascript - 如何删除特定文本短语的所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12077696/