在javascript数组</div>中的<div>标记下收集类名

时间:2012-08-30 04:25:47

标签: javascript jquery

<script type="text/javascript">
 $(document).ready(function () {

 });

</script>


<div id="input">
    <div class="feature draggable">Drag 1</div>
    <div class="feature resizable">Resize</div>
    <div class="feature downloadable">Download</div>
    <div class="feature draggable">Drag 2</div>
    <div class="feature trackable">Track</div>
    <div class="feature colorable">Color</div>
</div>​

我想将所有类元素存储在数组中的<div id="input">下。这样做的正确方法是什么?

JS小提琴:http://jsfiddle.net/gMjxu/

5 个答案:

答案 0 :(得分:4)

var classnames = $("#input div").map(function() { return this.className }).get();

如果元素上有多个类,则需要做一些额外的工作。

答案 1 :(得分:0)

  $(document).ready(function () {
        $.each($("#input div"), function() {
           alert($(this).prop('class'));
        });

 });    

这个小提琴

http://jsfiddle.net/dappledore/gMjxu/17/

答案 2 :(得分:0)

(function($) {
    $.fn.classes = function(f) {
        var c = [];
        $.each(this, function(i, v) {
            var _ = v.className.split(/\s+/);
            for (var j in _)'' === _[j] || c.push(_[j]);
        });
        c = $.unique(c);
        if ("function" === typeof f) for (var j in c) f(c[j]);
        return c;
    };
})(jQuery);

$(document).ready(function() {
    alert($('#input div').classes());
});​

$(document).ready(function () {
alert($('#input div').classes());
    });
</script>


<div id="input">
        <div class="feature draggable">Drag 1</div>
        <div class="feature resizable">Resize</div>
        <div class="feature downloadable">Download</div>
        <div class="feature draggable">Drag 2</div>
        <div class="feature trackable">Track</div>
        <div class="feature colorable">Color</div>
    </div>​

应该做的伎俩。 http://jsfiddle.net/FRhKS/

您最终得到了所有选定元素的唯一类数组。

答案 3 :(得分:0)

var classNames = []  

$('#input div').each(function(){
     classNames.push($(this).attr('class')) });

希望这就是你要找的东西。

答案 4 :(得分:0)

这里我有完整的演示箱和链接如下:

演示 http://codebins.com/bin/4ldqp7w

<强> HTML

<div id="input">
  <div class="feature draggable">
    Drag 1
  </div>
  <div class="feature resizable">
    Resize
  </div>
  <div class="feature downloadable">
    Download
  </div>
  <div class="feature draggable">
    Drag 2
  </div>
  <div class="feature trackable">
    Track
  </div>
  <div class="feature colorable">
    Color
  </div>
</div>
<input type="button" value="Show Classes" id="btn1" />

<强>的jQuery

$(function() {
    var c = [];
    $("#input div").each(function() {
        var cls = $(this).attr('class').split(' ');
        for (var j = 0; j < cls.length; j++) {
            if (cls[j] != '') {
                c.push(cls[j]);
            }
        }
    });

    $("#btn1").click(function() {
        if (c.length <= 0) {
            alert("No Class Exists...!");
        } else {
            for (var i = 0; i < c.length; i++) {
                alert(c[i]);
            }
        }
    });

});

演示 http://codebins.com/bin/4ldqp7w