我正在尝试创建一个函数,给定一个除法和一个类列表,然后在其中进行一些文本替换。
了解了 Firefox Dom 如何以不同的方式处理文本节点后,我了解到我必须使用 javascript 来循环遍历元素(与 nextSibling 是同级元素)。
我在脚本中遇到的最后一个障碍(您可以看到其中的一小部分)是获取类名。我需要类名,以便我可以过滤出替换的文本内容。
查看了所有答案后,在一位名叫 Ryan 的同事的帮助下,我们在 jquery 中重做了这个。
$(divid).find(".status_bar").each( function() {
var value = $.trim($(this).text());
// if value is not defined thru browser bugs do not replace
if (typeof(value) != 'undefined') {
// it is a text node. do magic.
for (var x = en_count; x > 0; x--) {
// get current english phrase
var from = en_lang[x];
// get current other language phrase
var to = other_lang[x];
if (value == from) {
console.log('Current Value ['+value+'] English ['+from+'] Translation ['+to+']');
value = to;
$(this).attr('value', to);
}
}
}
});
目前,除了文本替换之外,此功能适用于所有区域。
我最初在 jQuery 中这样做的原因是不确定我是否可以循环遍历元素,并避免 firefox 和文本节点的问题。
我正在对 div 内的所有元素进行循环,现在需要获取要循环的元素的类名。
然后我可以检查当前元素的类是否是一个,我需要做一些事情...
// var children = parent.childNodes, child;
var parentNode = divid;
// start loop thru child nodes
for(var node=parentNode.firstChild;node!=null;node=node.nextSibling){
var myclass = (node.className ? node.className.baseVal : node.getAttribute('class'));
}
但是这段获取类名的代码只能获取空值。
有什么建议吗?
对于那些想弄清楚重点是什么的人,请阅读这篇文章 JavaScript NextSibling Firefox Bug Fix我有代码可以在 Google Chrome 和 IE 中进行语言翻译。但是当我在 Firefox 中使用它,并尝试在 ajax 加载后翻译 div 内容时,由于空格问题而失败。
我真的不喜欢 jQuery 或纯 Javascript,我只想要一个可行的解决方案。
感谢大家的耐心等待。我个人认为我的描述非常清楚,如果不是,我很抱歉。我并不是想表现得晦涩难懂或让寻求帮助变得困难。但请不要侮辱我,暗示我试图把事情说得不清楚。
谢谢。
最佳答案
嗯...您有 jQuery 但不使用它?
$(divid).children(".yourSpecialClassName").each( function() {
doSomethingWith(this);
});
要获取 CSS 类属性值,可以这样做:
$(divid).children().each( function() {
alert(this.className);
});
根据您现在发布的功能,您需要这样的:
$(divid).find(".status_bar").each( function() {
$(this).text( function(i, text) {
var x = $.inArray(en_lang, $.trim(text));
if (x > -1) {
console.log('Current Value ['+text+'] English ['+en_lang[x]+'] Translation ['+other_lang[x]+']');
return other_lang[x];
}
return text;
});
});
请不要再使用“do magic”作为评论。这实在是太蹩脚了。
<小时/>编辑。这可以变得更加高效(删除多余的 console.log()
):
$(divid).find(".status_bar").each( function() {
// prepare dictionary en_lang => other_lang
var dict = {};
$.each(en_lang, function(x, word) { dict[word] = other_lang[x]; });
$(this).text( function(i, text) {
var t = $.trim(text);
return (t in dict) ? dict[t] : text;
});
});
关于javascript - 如何在元素循环内获取元素的类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2684431/