Javascript 如何查找与内部文本最近的标记
我试图找到一种方法来获取包含特定文本值的标记,问题是如果contains具有文本的子体,那么contains将返回元素。我只想要一个特别包含文本的 例如:Javascript 如何查找与内部文本最近的标记,javascript,jquery,Javascript,Jquery,我试图找到一种方法来获取包含特定文本值的标记,问题是如果contains具有文本的子体,那么contains将返回元素。我只想要一个特别包含文本的 例如: <table> <tr id='tag1'> <td>First Name $first$</td> <td>Last Name $last$</td> </tr> </table> 名字$Fir
<table>
<tr id='tag1'>
<td>First Name $first$</td>
<td>Last Name $last$</td>
</tr>
</table>
名字$First$
姓氏$Last$
我需要找到所有的标签有文字包装在$。使用:contains可以提供表和TR标记。我只想要TD标签
请注意,这些可能是div而不是TDs,所以我也不能专门搜索TD
任何人都有一些巧妙的想法吗?为了提高速度和处理嵌入式子元素,您可能会发现使用纯JS和只搜索文本节点都更快、更实用。我有一个
treewalk()
函数,我对该函数进行了调整,在某个父节点中的所有文本节点上调用回调,然后您可以使用回调在这些文本节点中执行任何您想要的操作
下面是这个概念的一个工作演示,它用映射对象中的值替换了$first$
和$last$
下面是更通用的代码,它只为您构建一个节点和匹配项列表:
var treeWalkTextNodes = (function() {
// create closure for constants
var skipTags = {"SCRIPT": true, "IFRAME": true, "OBJECT": true,
"EMBED": true, "STYLE": true, "LINK": true, "META": true};
return function(parent, fn, data) {
var node = parent.firstChild, nextNode;
while (node && node != parent) {
if (node.nodeType === 3) {
if (fn(node, data) === false) {
return false ;
}
}
// if element with children and not a skipTag type element, then
// iterate through it's children
if (node.nodeType === 1 && node.firstChild && !(node.tagName && skipTags[node.tagName])) {
node = node.firstChild;
} else if (node.nextSibling) {
node = node.nextSibling;
} else {
// no child and no nextsibling
// find parent that has a nextSibling
while ((node = node.parentNode) != parent) {
if (node.nextSibling) {
node = node.nextSibling;
break;
}
}
}
}
}
})();
function replace$Data(parent, map) {
var dollars = /\$(.*?)\$/;
treeWalkTextNodes(parent, function(node, data) {
// node is the text node
// node.parentNode is the element containing the text node
var str, found = false;
str = node.nodeValue.replace(dollars, function(match, p1) {
if (p1 in map) {
found = true;
return map[p1];
} else {
return match;
}
});
if (found) {
node.nodeValue = str;
}
});
}
// then to call this, you would do something like this:
var matchMap = {
first: "John",
last: "Kennedy"
};
replace$Data(document.body, matchMap);
显然,您可以在回调函数中实现您自己的逻辑-我刚刚选择展示一个实现,它用映射中的其他文本替换$signs之间的文本。为什么内容在$和$之间,可能有更好的方法您是老板!!非常感谢。