0
<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">in 数组下。正确的方法是什么?

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

4

5 回答 5

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

如果一个元素上有多个类,您将不得不做一些额外的工作。

于 2012-08-30T04:38:28.790 回答
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

于 2012-08-30T10:40:14.963 回答
0
  $(document).ready(function () {
        $.each($("#input div"), function() {
           alert($(this).prop('class'));
        });

 });    

这个小提琴

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

于 2012-08-30T04:31:03.057 回答
0
var classNames = []  

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

希望这是您正在寻找的。

于 2012-08-30T04:44:32.103 回答
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/

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

于 2012-08-30T04:42:19.267 回答