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

发布于 2024-08-30 05:45:21 字数 1946 浏览 3 评论 0原文

我正在尝试创建一个函数,给定一个除法和一个类列表,然后在其中进行一些文本替换。

在了解了 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 错误修复 我有代码可以在 Google Chrome 和 IE 中进行语言翻译。但是当我在 Firefox 中使用它,并尝试在 ajax 加载后翻译 div 内容时,由于空格问题而失败。

我真的没有 jQuery 或纯 Javascript 的偏好,我只想要一个可行的解决方案。

感谢大家的耐心等待。我个人认为我的描述非常清楚,如果不是,我很抱歉。我并不是想表现得晦涩难懂或让寻求帮助变得困难。但请不要侮辱我,暗示我试图把事情说得不清楚。

谢谢。

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.

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.

        $(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.

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.

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.

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. 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.

I really don't have a preference of jQuery or Pure Javascript, I just want a working solution.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

池木 2024-09-06 05:45:21

嗯...您有 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;
  });
});

Hm... You have jQuery but don't use it?

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

To get the CSS class attribute value, this will do:

$(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.


EDIT. This can be made much more efficient (superfluous console.log() removed):

$(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;
  });
});
白龙吟 2024-09-06 05:45:21

如果你使用jquery,你可以这样做:

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

if you are using jquery you can do this:

$("#myDiv").find("*").each(
   function(){
      var myclass = $(this).attr("class");
   }
);
相思故 2024-09-06 05:45:21

您的示例代码没有意义。

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

“value”是标签的属性,而不是文本内容。

您真的打算这样做吗?

$(this).text(to);

另外,您已经重新编辑了您的问题,但您仍然尝试使用非 jQuery 方法循环遍历子节点。你说“我在脚本中遇到的最后一个障碍(你看到其中的一小部分)是获取类名。我需要类名,以便我可以过滤出替换的文本内容。”

如果您使用 jQuery,则完全没有必要循环遍历任何内容来获取类名。您只需首先使用正确的 选择器 即可。

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

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. 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. 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);
            }
        }
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文