简体   繁体   English

如何获得同一个类的多个元素?

[英]How to get multiple elements with same class?

I have some HTML I want to process with jquery. 我有一些要使用jquery处理的HTML。

Pretty simple but I cannot get around getting all the elements with the same class: 非常简单,但是我无法绕过使用同一类的所有元素:

<div class="myclass on"></div>
<div class="myclass off"></div>
<div class="myclass on"></div>

If I do this 如果我这样做

$(".myclass") $( “MyClass的”)

I get only one. 我只有一个。 Any help? 有什么帮助吗?

EDIT 编辑

I actually only want the 'myclass on' to nest some html in each one to get this: 我实际上只希望'myclass on'在每一个中嵌套一些html来实现这一点:

<div class="myclass on"><img src="bar.png"></div>
<div class="myclass off"></div>
<div class="myclass on"><img src="bar.png"></div>

Maybe you are just not combining two classes correctly in the selector? 也许您只是没有在选择器中正确组合两个类? Because this works: 因为这有效:

$(".myclass.on").html('<img src="bar.png">');

http://jsfiddle.net/zjErL/1/ (Thanks Arun for the initial jsfiddle) http://jsfiddle.net/zjErL/1/ (感谢Arun最初的jsfiddle)

Try using for manipulating each element separately. 尝试用于分别处理每个元素。 Just the class .on should be sufficient for the selector. 选择器仅使用类.on就足够了。

  $('.on').each(function(index){
    $(this).html('<img src="bar.png">');
  });

The documentation http://api.jquery.com/each/ 文档http://api.jquery.com/each/

May be u did some wrong. 可能是您做错了。 If you have done $('.myclass') it must work. 如果您完成了$('。myclass'),那么它必须可以工作。 Can you post your codes. 您可以发布代码吗?

This works for me like a charm. 这对我来说就像一种魅力。

$(function(){
    $('.myclass').SOMEEVENT(function(e){ // or use div.myclass without problem 
        // do something. It must work.
    });
});

OR if you want to iterate through each element, you can use .each 或者,如果要遍历每个元素,则可以使用.each

$(function(){
    $.each($('.myclass'),function(ind, val){
        // do something.
    });
});

OR if you want to use additional class like .on or .off 或者,如果您想使用其他类,如.on或.off

$(function(){
    $.each($('.myclass.on'),function(ind, val){
        // do something.
    });
});

EDIT: 编辑:
To add image to myclass on , you can simply do this 要将图像添加到myclass on ,您只需执行此操作

$(function(){
    $('.myclass.on').html('Your NEW Adding Tag here');
});

$(".myclass.on").css('color', 'red'); $(“。myclass.on”)。css('color','red');

Should select elements with both classes. 应该同时选择两个类的元素。

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

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