您对 a 在模板中的位置有任何限制吗?
例如,这是您将模板中所有 SPAN 中的所有 a 大写的方式:
Template.complicated.rendered = function() {
this.findAll('span').each(function(idx, element) {
$(element).html( $(element).html().replace(/a/g, 'A');
});
};
如果要遍历所有顶级节点,可以这样做:
Template.complicated.rendered = function() {
var node = this.firstNode;
while(true) {
// manipulate with node
//
// for example, get all text nodes within in
// and replace a's with A's
if(node === template.lastNode) return;
node = node.nextSibling;
}
}
但是,您需要小心使用此方法,并且只替换叶节点的内容。如果你改变每一个a
,你可能会改变你不想改变的链接网址。此外,更改所有 DOM,而不仅仅是文本节点的内容,可能会激怒 Meteor 之神。
EDIT: Combined with How do I select text nodes with jQuery? , this code will upcase all a's in all text nodes within the template:
Template.complicated.rendered = function() {
var node = this.firstNode;
while(true) {
_.each(getTextNodesIn(node, false), function(textNode) {
textNode.nodeValue = textNode.nodeValue.replace(/a/g, 'A');
});
if(node === template.lastNode) return;
node = node.nextSibling;
}
}