简体   繁体   English

如何在元素循环内获取元素的className?

[英]How do I get element's className inside loop of elements?

I am trying to create a function that given a divid, and a list of classes, will then do some text replacing inside them. 我正在尝试创建一个给定分隔符和一个类列表的函数,然后在其中替换一些文本。

Having learned of how Firefox Dom is handling text nodes differently, I read that I had to use javascript to loop through the elements, sibling to nextSibling. 了解了Firefox Dom如何以不同方式处理文本节点后,我读到我必须使用javascript遍历元素,将其同级为nextSibling。

The last obstacle I had in my script, of which you see a small portion of, is getting the classname. 我在脚本中遇到的最后一个障碍(就是一小部分)是获取类名。 I need the class name so that I can filter down what content get's text replaced. 我需要类名,以便可以筛选出替换为文本的内容。

Having looked all the answers, and with the help of a co-worker named Ryan at work, we have redone this in jquery. 看完所有答案之后,并在一个名为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);
                }
            }
        }
    });

This currently works in all areas, except in the replacing of text. 目前,这在所有领域都适用,除了替换文字。

The reason I had originally with doing this in jQuery, had to be not sure I could loop thru elements, and avoid the problem with firefox and text nodes. 我最初在jQuery中执行此操作的原因,是不确定我是否可以遍历元素,并避免使用Firefox和文本节点的问题。

I am doing a loop of all elements inside a div, and I now need to get the classname of the element that I am looping by. 我正在对div中的所有元素进行循环,现在我需要获取要循环通过的元素的类名。

Then i can check if the current element's class is one, I need to do something with... 然后我可以检查当前元素的类是否为一,我需要使用...

 // 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'));

    }

But this code for getting the classname only get's null values. 但是此用于获取类名的代码仅获取null值。

Any suggestions? 有什么建议么?

For those of you who are trying to figure out what the whole point is, read this JavaScript NextSibling Firefox Bug Fix I have code that does my language translation that works in Google Chrome and IE. 对于那些试图弄清重点的人,请阅读此JavaScript NextSibling Firefox Bug Fix我有执行我的语言翻译的代码,可在Google Chrome和IE中使用。 But when I use it in Firefox, and try to translate div content after ajax has loaded it, it fails because of the whitespace issue. 但是,当我在Firefox中使用它并尝试在ajax加载它后转换div内容时,由于空白问题,它失败了。

I really don't have a preference of jQuery or Pure Javascript, I just want a working solution. 我真的没有jQuery或Pure Javascript的偏好,我只想要一个可行的解决方案。

Thank you all for being patient. 谢谢大家的耐心等待。 I personally thought I was extremely clear in my description, I apologize if it wasn't. 我个人认为自己的描述非常清楚,如果没有,我深表歉意。 I wasn't trying to be obscure or make it difficult to get help. 我并不想变得晦涩难懂或难以获得帮助。 But please don't insult me, by implying I am trying to make it unclear. 但是请不要侮辱我,暗示我正在努力使之不清楚。

Thanks. 谢谢。

Hm... You have jQuery but don't use it? 嗯...您有jQuery但不使用它吗?

$(divid).children(".yourSpecialClassName").each( function() {
  doSomethingWith(this);
});

To get the CSS class attribute value, this will do: 要获取CSS类属性值,可以这样做:

$(divid).children().each( function() {
  alert(this.className);
});

Based on the function you posted now, you want this: 根据您现在发布的功能,您需要:

$(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;
  });
});

And please, don't ever use "do magic" as a comment again. 而且,请不要再使用“做魔术”作为注释。 This is incredibly lame. 这真是la脚。


EDIT. 编辑。 This can be made much more efficient (superfluous console.log() removed): 可以提高效率(删除了多余的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;
  });
});

if you are using jquery you can do this: 如果您使用的是jquery,则可以执行以下操作:

$("#myDiv").find("*").each(
   function(){
      var myclass = $(this).attr("class");
   }
);

Your sample code doesn't make sense. 您的示例代码没有意义。

$(this).attr('value', to);

'value' is an attribute of the tag, not the text content. “值”是标签的属性,而不是文本内容。

Did you really mean to do this instead? 您真的是要这样做吗?

$(this).text(to);

Also, you've re-edited your question, but you're still trying to loop through the child nodes using non-jQuery methods. 另外,您已经重新编辑了问题,但是您仍在尝试使用非jQuery方法遍历子节点。 You said "The last obstacle I had in my script, of which you see a small portion of, is getting the classname. I need the class name so that I can filter down what content get's text replaced." 您说:“我在脚本中遇到的最后一个障碍(就是一小部分)是获取类名。我需要使用类名,以便能够过滤掉替换内容后的文本。”

If you are using jQuery it is completely unnecessary to loop through anything to get a class name. 如果您使用的是jQuery,则完全不需要遍历任何内容来获取类名。 You simply have to use a proper selector in the first place. 您只需要首先使用适当的选择器

 $(divid).find(".status_bar.replaceme").each( function() {  
    // .replaceme is whatever class you're using for the stuff you want to change
    // .status_bar.replaceme matches all elements with BOTH status_bar and replaceme classes

    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.


        // NOTE: The following is inefficient but I won't fix it. 
        //       You're better off using an associative array

        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;    <-- useless, get rid of it.
                $(this).text(to);
                // or $(this).html(to);
            }
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM